快速排序:快速排序是經典的排序算法之一,它是冒泡排序的升級版。
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。
首先觀察每一趟排序的效果:
原始序列:[84, 17, 26, 30, 62, 83, 5, 79, 45, 85]
[45, 17, 26, 30, 62, 83, 5, 79, 84, 85]
[5, 17, 26, 30, 45, 83, 62, 79, 84, 85]
[5, 17, 26, 30, 45, 83, 62, 79, 84, 85]
[5, 17, 26, 30, 45, 83, 62, 79, 84, 85]
[5, 17, 26, 30, 45, 83, 62, 79, 84, 85]
[5, 17, 26, 30, 45, 83, 62, 79, 84, 85]
[5, 17, 26, 30, 45, 79, 62, 83, 84, 85]
[5, 17, 26, 30, 45, 62, 79, 83, 84, 85]
[5, 17, 26, 30, 45, 62, 79, 83, 84, 85]
[5, 17, 26, 30, 45, 62, 79, 83, 84, 85]
最終結果:[5, 17, 26, 30, 45, 62, 79, 83, 84, 85]
python代碼實現:
from random import randint
l = [randint(0, 100) for x in range(10)]
print l
def q_sort(l, left, right):
if left > right:
return
i = left
j = right
flag = l[left]
while i < j:
while i < j and flag <= l[j]:
j = j - 1
l[i] = l[j]
while i < j and flag >= l[i]:
i = i + 1
l[j] = l[i]
l[i] = flag
print l
q_sort(l, left, i - 1)
q_sort(l, i + 1, right)
return l
print q_sort(l, 0, len(l) - 1)