请看讲解:快速排序 - python版超详细讲解
### 所有的交换都是跟哨兵换的。
def quick_sort(nums, l, r):
if l >= r: # >=
return
i = partition(nums, l, r) # 返回值是哨兵元素下标
quick_sort(nums, l, i - 1)
quick_sort(nums, i + 1, r)
def partition(nums, l, r):
base = nums[l] # 哨兵
i, j = l, r
while i < j:
while i < j and nums[j] > base: j -= 1
nums[i] = nums[j]
while i < j and nums[i] < base: i += 1
nums[j] = nums[i]
nums[i] = base # 此时 i == j, 将哨兵放到此位置
return i
# nums = [5,7,1,8,3]
nums = [1,2] # quick_sort(nums, 0, -1)
quick_sort(nums, 0, len(nums)-1)
print(nums)
### 只有最后一个确定的位置的时候,才是跟哨兵换的。大部分都是nums[i], nums[j] 交换的
def quick_sort(nums, l, r):
# 子数组长度为 1 时终止递归
if l >= r: return
# 哨兵划分操作
i = partition(nums, l, r)
# 递归左(右)子数组执行哨兵划分
quick_sort(nums, l, i - 1)
quick_sort(nums, i + 1, r)
def partition(nums, l, r):
# 以 nums[l] 作为基准数 ############################################
i, j = l, r
while i < j:
while i < j and nums[j] >= nums[l]: j -= 1
while i < j and nums[i] <= nums[l]: i += 1
nums[i], nums[j] = nums[j], nums[i]
nums[l], nums[i] = nums[i], nums[l]
return i
# 调用
nums = [3, 4, 1, 5, 2]
quick_sort(nums, 0, len(nums) - 1)
print(nums)