快速排序的基本思想:设要排序的数组是A[0]……A[N-1],首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法,也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。
快速排序的平均时间复杂度是:O(n)=nLog(n)
def quick_sort(lists,begin,end):
if begin>=end:
return lists
keys=lists[begin] #随机选择一个比较的枢轴值,这里选择了第一个
low=begin
high=end
while begin<end:
while begin<end and lists[end]>=keys:
end-=1
lists[begin]=lists[end]
while begin<end and lists[begin]<=keys:
begin+=1
lists[end]=lists[begin]
lists[begin]=keys
quick_sort(lists,low,begin-1)
quick_sort(lists,begin+1,high)
return lists
if __name__ == "__main__":
lists=[10,9,8,7,6,5,4,3,2,1]
print("sort before:")
for i in lists:
print(i)
quick_sort(lists,0,len(lists)-1)
print("sort after:")
for i in lists:
print(i)
def quick_sort(lists,begin,end):
if begin>=end:
return lists
keys=lists[begin] #随机选择一个比较的枢轴值,这里选择了第一个
low=begin
high=end
while begin<end:
while begin<end and lists[end]>=keys:
end-=1
lists[begin]=lists[end]
while begin<end and lists[begin]<=keys:
begin+=1
lists[end]=lists[begin]
lists[begin]=keys
quick_sort(lists,low,begin-1)
quick_sort(lists,begin+1,high)
return lists
if __name__ == "__main__":
lists=[10,9,8,7,6,5,4,3,2,1]
print("sort before:")
for i in lists:
print(i)
quick_sort(lists,0,len(lists)-1)
print("sort after:")
for i in lists:
print(i)