https://www.cnblogs.com/feichangnice/p/5334195.html
算法导论上的快速排序采用分治算法,步骤如下:
1.选取一个数字作为基准,可选取末位数字
2.将数列第一位开始,依次与此数字比较,如果小于此数,将小数交换到左边,最后达到小于基准数的在左边,大于基准数的在右边,分为两个数组
3.分别对两个数组重复上述步骤
其中一次排序步骤如下:
伪码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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实现代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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]
性能分析以后做