1、 演算法描述:
1.先從數列中取出一個數作為基準數。
2.分割槽過程,將比這個數大的數全放到它的右邊,小於或等於它的數全放到它的左邊。
3.再對左右區間重複第二步,直到各區間只有一個數。
2、python程式碼
#!/usr/bin/python # -*- coding: utf-8 -*- def sub_sort(array,low,high): key = array[low] while low < high: while low < high and array[high] >= key: high -= 1 while low < high and array[high] < key: array[low] = array[high] low += 1 array[high] = array[low] array[low] = key return low def quick_sort(array,low,high): if low < high: key_index = sub_sort(array,low,high) quick_sort(array,low,key_index) quick_sort(array,key_index+1,high) if __name__ == '__main__': array = [8,10,9,6,4,16,5,13,26,18,2,45,34,23,1,7,3] print array quick_sort(array,0,len(array)-1) print array
結果:
[8, 10, 9, 6, 4, 16, 5, 13, 26, 18, 2, 45, 34, 23, 1, 7, 3]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 16, 18, 23, 26, 34, 45]