# 递归实现
def quick_sort(arr: list) -> list:
if len(arr) <= 1:
# 基线条件
return arr
else:
# 递归条件
mid = len(arr) // 2
pivot = arr[mid]
# less = [i for i in arr[1:] if i <= pivot]
# greater = [i for i in arr[1:] if i > pivot]
less = []
greater = []
for i in (arr[:mid] + arr[mid+1:]):
if i <= pivot:
less.append(i)
else:
greater.append(i)
return quick_sort(less) + [pivot] + quick_sort(greater)
def quick_sort2(arr: list) -> list:
# 如果使用 第0个元素作为基准点,在数组本身有序的情况下, less 数组始终为空,会导致栈的高度为 N
# 每次执行循环两次筛选,会导致每层复杂度为2N 大 O表达式计算时会将常数忽略
if len(arr) <= 1:
return arr
return quick_sort2([i for i in arr[1:] if i <= arr[0]]) + [arr[0]] + quick_sort2(
[i for i in arr[1:] if i > arr[0]])
if __name__ == '__main__':
print(quick_sort([6, 3, 14, 56, 3, 13, 1]))
package main
import (
"fmt"
"math/rand"
)
func main() {
arr := []int{3, 1, 2, 5, 4, 6, 9, 7, 10, 8}
quickSort(arr)
fmt.Println(arr)
}
func quickSort(a []int) {
if len(a) < 2 {
return
}
left, right := 0, len(a)-1
pivot := rand.Int() % len(a)
a[pivot], a[right] = a[right], a[pivot]
for i := range a {
if a[i] < a[right] {
a[left], a[i] = a[i], a[left]
left++
}
}
a[left], a[right] = a[right], a[left]
quickSort(a[:left])
quickSort(a[left+1:])
}
def quick_sort(array, left, right):
if left >= right:
return
low = left
high = right
key = array[low]
while left < right:
while left < right and array[right] > key:
right -= 1
array[left] = array[right]
while left < right and array[left] <= key:
left += 1
array[right] = array[left]
array[right] = key
quick_sort(array, low, left - 1)
quick_sort(array, left + 1, high)
if __name__ == '__main__':
l = [47, 5, 3, 5, 6, 87, -7, 2]
quick_sort(l, 0, len(l) - 1)
print(l)
package main
import "fmt"
func main() {
arr := []int{5, 3, 1, 5, 6, 7, 4, 3, -1}
fmt.Println(quickSort(arr))
}
// 递归实现
func quickSort(arr []int) []int {
if len(arr) <= 1 {
return arr
} else {
mid := len(arr) / 2
pivot := arr[mid]
less := make([]int, 0)
greater := make([]int, 0)
for _, v := range append(arr[:mid], arr[mid+1:]...) {
if v <= pivot {
less = append(less, v)
} else {
greater = append(greater, v)
}
}
return append(append(quickSort(less), pivot ), quickSort(greater)...)
}
}