算法導論上的快速排序采用分治算法,步驟如下:
1.選取一個數字作為基准,可選取末位數字
2.將數列第一位開始,依次與此數字比較,如果小於此數,將小數交換到左邊,最后達到小於基准數的在左邊,大於基准數的在右邊,分為兩個數組
3.分別對兩個數組重復上述步驟
其中一次排序步驟如下:

偽碼實現:
QuickSort(A,p,r)
if p<r
then q = Partition(A,p,r)
QucikSort(A,p,q-1)
QucikSort(A,q+1,r)
Partition(A,p,r)
x=A[r]
i=p-1
for j from p to r-1
if A[j]<=x
then i=i+1
exchange A[i],A[j]
exchange A[i+1],A[r]
return i+1
Python實現代碼如下:
def QuickSort(arr,firstIndex,lastIndex):
if firstIndex<lastIndex:
divIndex=Partition(arr,firstIndex,lastIndex)
QuickSort(arr,firstIndex,divIndex)
QuickSort(arr,divIndex+1,lastIndex)
else:
return
def Partition(arr,firstIndex,lastIndex):
i=firstIndex-1
for j in range(firstIndex,lastIndex):
if arr[j]<=arr[lastIndex]:
i=i+1
arr[i],arr[j]=arr[j],arr[i]
arr[i+1],arr[lastIndex]=arr[lastIndex],arr[i+1]
return i
arr=[1,4,7,1,5,5,3,85,34,75,23,75,2,0]
print("initial array:\n",arr)
QuickSort(arr,0,len(arr)-1)
print("result array:\n",arr)
運行結果如下:
initial array:
[1, 4, 7, 1, 5, 5, 3, 85, 34, 75, 23, 75, 2, 0]
result array:
[0, 1, 1, 2, 3, 4, 5, 5, 7, 23, 34, 75, 75, 85]
性能分析以后做
