对于包含n个数的输入数组而言,快速排序是一种最坏情况时间复杂度为 Θ ( n 2 ) \Theta(n^2) Θ(n2)的排序算法,但是它的平均性能非常好,它的期望时间复杂度是 Θ ( n l g n ) \Theta(n\ lgn) Θ(n lgn),而且 Θ ( n l g n ) \Theta(n\ lgn) Θ(n lgn)中隐含的常数因子非常小。
Python 实现代码:
import numpy as np
def quick_sort(A,p,r):
if p<r:
q = partition(A,p,r)
quick_sort(A,p,q-1)
quick_sort(A,q+1,r)
def partition(A,p,r):
x = A[r]
i = p-1
for j in range(p,r):
if A[j] <= x:
i = i+1
t = A[j]
A[j] = A[i]
A[i] = t
A[r] = A[i+1]
A[i+1] = x
return(i+1)
a = [2,3,8,1,1,6,5,8,13,4,15,6,17,9]
a = np.array(a)
quick_sort(a,0,len(a)-1)
print(a)
'''
此处为程序输出:
[ 1 1 2 3 4 5 6 6 8 8 9 13 15 17]
'''