首页 > 代码库 > 快速排序

快速排序

发现自己写起来很不顺手,得从最右边找出pivot元素是最方便的!

以最左边的元素作为pivot的代码,看到好多坑:

def qsort(arr, left, right):
    if left >= right:
        return
    pivot = arr[left]
    p = left+1
    for i in range(left+1, right+1):
        if arr[i] < pivot:
            arr[i], arr[p] = arr[p], arr[i]
            p += 1
    partition_index = p-1
    arr[left], arr[partition_index] = arr[partition_index], arr[left]
    qsort(arr, left, partition_index-1)
    qsort(arr, partition_index+1, right)

def qsort2(arr, left, right):
    if left >= right:
        return
    pivot = arr[right]
    index = left
    for i in range(left, right):
        if arr[i] < pivot:
            arr[i], arr[index] = arr[index], arr[i]
            index += 1
    arr[index], arr[right] = arr[right], arr[index]
    qsort(arr, left, index-1)
    qsort(arr, index+1, right)

from random import randint
a=[]
for i in range(30):
    a.append(randint(0, 20))

print a
qsort2(a, 0, len(a)-1)
print a

输出:

[12, 4, 19, 2, 15, 13, 16, 2, 4, 1, 0, 13, 10, 1, 11, 15, 13, 7, 8, 6, 12, 20, 18, 20, 20, 3, 7, 5, 11, 11]
[0, 1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 7, 8, 10, 11, 11, 11, 12, 12, 13, 13, 13, 15, 15, 16, 18, 19, 20, 20, 20]

 

快速排序