Python快排
# coding: utf-8
def quickSort(alist):
quickSortHelper(alist, 0, len(alist)-1)
def quickSortHelper(alist, first, last):
if first < last:
splitPoint = partition(alist, first, last)
quickSortHelper(alist, first, splitPoint-1)
quickSortHelper(alist, splitPoint+1, last)
def partition(alist, first, last):
pivotvlue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvlue: # bugfix: 先比较index, 不然数组会越界
leftmark += 1
while rightmark >= leftmark and alist[rightmark] >= pivotvlue:
rightmark -= 1
if leftmark > rightmark:
done = True
else:
alist[leftmark], alist[rightmark] = alist[rightmark], alist[leftmark]
alist[rightmark], alist[first] = alist[first], alist[rightmark]
return rightmark
alist = [54,26,93,17,77,31,44,55,20]
alist2 = [1]
quickSort(alist2)
print(alist2)
if __name__ == "__main__":
test_data = [3,2,111,3,-1,0,0,1,0,2,4]
res_stable = sorted(test_data)
quickSort(test_data)
print(test_data)
print(res_stable)
assert all(map(lambda x: x[0] == x[1], zip(res_stable, test_data)))
解压密码: detechn或detechn.com
免责声明
本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。
本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。
本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。