基本快速排序
def quickSort(s, start, end):
if start < end:
index = basicSort(s, start, end)
quickSort(s, start, index - 1)
quickSort(s, index + 1, end)
def basicSort(s, start, end):
"""
基本的快速排序,i作爲小於temp值和大於temp值的分界點。index<=i的值都是小於temp的值
index > i 的元素都是大於等於temp的
:param s:
:param start: 閉區間
:param end: 閉區間
:return:
"""
temp = s[start]
j = start
for i in range(start + 1, end + 1):
# 如果i位置的元素小於temp,那就把它放在j+1的位置
if s[i] < temp:
s[j + 1], s[i] = s[i], s[j + 1]
j += 1
# 最後j指向的位置是一個小於temp的元素,可以將其和start位置的元素
s[start], s[j] = s[j], s[start]
return j
二路快速排序
def quickSort(s, start, end):
if start < end:
index = two_sort(s, start, end)
quickSort(s, start, index - 1)
quickSort(s, index + 1, end)
def two_sort(nums, start, end):
temp = nums[start]
i = start + 1 # 起點從start+1開始
j = end
while True:
while i <= end and nums[i] < temp: # 利用短路條件,比較不要帶等號
i += 1
while j >= start + 1 and nums[j] > temp:
j -= 1
if i > j: # 跳出不要帶等號
break
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
nums[start], nums[j] = nums[j], nums[start]
return j
注意:無論基本快排和二路快排,和temp比較的時候都不帶等號
三路快速排序
def threeSort(self, s, start, end): # 使用閉區間
"""
:param s:
:param start:
:param end:
:return:
"""
if start > end:
return
temp = s[start]
lt = start # 小於temp的範圍是 [start,lt-1]
gt = end + 1 # 等於temp的範圍是 [lt+1,gt-1]
i = start + 1 # 大於temp的範圍是[gt,r]
# i到gt-1的數據,狀態不明確
while i < gt:
if s[i] < temp:
s[i], s[lt + 1] = s[lt + 1], s[i]
lt += 1
i += 1
elif s[i] > temp:
s[i], s[gt - 1] = s[gt - 1], s[i]
gt -= 1
else:
i += 1
s[start], s[lt] = s[lt], s[start]
self.threeSort(s, start, lt - 1)
self.threeSort(s, gt, end)