快速排序
平均时间复杂度: nlogn
最为常用的排序算法
def quick_sort(data, start, end): # 快排原地排序,直接对原list排序,没有返回值 if start>=end: return # 开始结束索引不能破坏 left, right = start, end mid = start + (end-start)//2 # 避免最坏情况出现 pivot = data[mid] while left <= right: while left <= right and data[left]<pivot: left += 1 while left <= right and data[right]>pivot: right -= 1 # 两头找到均不满足条件的数,需要互换区间 if left <= right: data[left], data[right] = data[right], data[left] left += 1 right -= 1 # 小范围内再排序 quick_sort(data, start, right) quick_sort(data, left, end) nums = [33,2,11,8,7,12] quick_sort(nums, 0, len(nums)-1) nums
def quick_sort(data, start, end): # 快排原地排序,直接对原list排序,没有返回值 if start>=end: return # 开始结束索引不能破坏 left, right = start, end mid = start + (end-start)//2 # 避免最坏情况出现 pivot = data[mid] while left <= right: print("###",left, right, data) while left <= right and data[left]<pivot: left += 1 while left <= right and data[right]>pivot: right -= 1 # 两头找到均不满足条件的数,需要互换区间 if left <= right: data[left], data[right] = data[right], data[left] left += 1 right -= 1 # print(start, right) # 小范围内再排序,上层循环的停止条件是right<left,所以此时最左端是right,右端是left quick_sort(data, start, right) quick_sort(data, left, end) nums = [33,2,11,8,7,12] quick_sort(nums, 0, len(nums)-1) nums
v3
class Solution: def sortArray(self, nums: List[int]) -> List[int]: if not nums: return self.quick_sort(nums, 0, len(nums)-1) return nums def quick_sort(self, nums, start, end): if start >= end: return left, right = start, end mid = start + (end-start)//2 piovt = nums[mid] while left <= right: while left <= right and nums[left]<piovt: left += 1 while left <= right and nums[right]>piovt: right -= 1 if left <= right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 self.quick_sort(nums, start, right) self.quick_sort(nums, left, end)
时刻记着自己要成为什么样的人!