介紹
快速排序通常明顯比同爲
步驟
- 從數列中挑出一個元素作爲基準數。
- 分區過程,將比基準數大的放到右邊,小於或等於它的數都放到左邊。
- 再對左右區間遞歸執行第二步,直至各區間只有一個數。
代碼
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 16:10:13 2016
@author: zang
"""
from matplotlib import pyplot as plt
import random
def quickSort(unsortedList):
if len(unsortedList)<2:
return unsortedList
less=[]
greater=[]
middle=unsortedList.pop(0)
for item in unsortedList:
if item < middle:
less.append(item)
else:
greater.append(item)
return quickSort(less)+[middle]+quickSort(greater)
def plotScatter(inputList):
plt.scatter(range(len(inputList)),inputList)
plt.show()
if __name__ == "__main__":
num_list = range(1000)
unsortedList = random.sample(num_list, 30)
print "unsortedList:"
plotScatter(unsortedList)
print unsortedList
sortedList = quickSort(unsortedList)
print "sortedList:"
plotScatter(sortedList)
print sortedList
測試
輸入
[918, 965, 651, 275, 993, 729, 952, 764, 947, 840, 916, 299, 213, 384, 263, 606, 641, 17, 185, 939, 118, 610, 382, 816, 344, 60, 236, 26, 775, 399]
輸出
[17, 26, 60, 118, 185, 213, 236, 263, 275, 299, 344, 382, 384, 399, 606, 610, 641, 651, 729, 764, 775, 816, 840, 916, 918, 939, 947, 952, 965, 993]
分析
情況 | 性能 |
---|---|
Worst case performance: | |
Best case performance: | |
Average case performance: | |
Worst case space complexity: |