在數組中隨機選取一個元素 p,一次排序後使得p前面的元素都比p小,p後面的元素都比p大。
而後再將p前面和後面的元素分別進行剛纔一樣的排序。如此反覆執行,最後將獲得一個有序的數組。python
假設有數組 6 5 7 2 3 9 1
若是每次都選取第一個元素 爲 p,算法
排序元素 6 5 7 2 3 9 1
選取 p = 3
排序後要求 2 1 3 5 6 9 7
3前面的順序不重要 重要的是 3前面的元素都比3小,後面的都比3 大數組
排序元素 2 1 選取 p = 2 排序後要求 1 2
2前面的元素都比2小,後面的都比2 大bash
排序元素 5 6 9 7 選取 p = 5 排序後要求 5 6 9 7
5前面的元素都比5小,後面的都比5 大ui
排序元素 1 選取 p = 1 排序後要求 1
1前面的元素都比1小,後面的都比1 大spa
只須要排序後 使得 p前面的元素都比p小,後面的都比p大。設置兩個指針 p_start 指向數組頭部,p_end指向數組尾部。從尾部開始向前找到一個比p小的元素,再從頭開始找一個比p大的元素,而後交換他們兩個的位置。如此反覆,最後總會有一個時刻 p_start = p_end,這個位置就是p應該在的位置。指針
代碼實現 pythoncode
def sort(datas, start_index, end_index):
pivot = datas[start_index]
while start_index < end_index:
while datas[end_index] > pivot and start_index < end_index:
end_index -= 1
while datas[start_index] <= pivot and start_index < end_index:
start_index += 1
if start_index < end_index:
temp = datas[start_index]
datas[start_index] = datas[end_index]
datas[end_index] = temp
datas[start_index] = pivot
return start_index
複製代碼
datas1 = [1, 2, 4, 6, 3, 1, 3, 43, 547, 123, 436, 57, 98, 976, 543, 2112, 378988, 7654321, 32]
def sort(datas, start_index, end_index):
pivot = datas[start_index]
while start_index < end_index:
while datas[end_index] > pivot and start_index < end_index:
end_index -= 1
while datas[start_index] <= pivot and start_index < end_index:
start_index += 1
if start_index < end_index:
temp = datas[start_index]
datas[start_index] = datas[end_index]
datas[end_index] = temp
datas[start_index] = pivot
return start_index
def quicSort(datas, start_index, end_index):
if start_index < end_index:
mid_index = sort(datas, start_index, end_index)
quicSort(datas, start_index, mid_index - 1)
quicSort(datas, mid_index + 1, end_index)
quicSort(datas1, 0, len(datas1) - 1)
print(datas1)
複製代碼