动态git可以看 :https://leetcode.cn/problems/sort-an-array/solutions/179370/python-shi-xian-de-shi-da-jing-dian-pai-xu-suan-fa/
选择排序
def selection_sort(nums):n = len(nums)for i in range(n):for j in range(i, n):if nums[i] > nums[j]:nums[i], nums[j] = nums[j], nums[i]return nums
为什么只交换严格小于的呢?
插入排序
class Solution:def sortArray(self, nums: List[int]) -> List[int]:for i in range(1, len(nums)):while i > 0 and nums[i] < nums[i - 1]:nums[i-1], nums[i] = nums[i], nums[i-1]i -= 1return nums
注意使用里面的while loop来实现一直交换的效果
冒泡排序
class Solution:def sortArray(self, nums: List[int]) -> List[int]:for i in range(len(nums)):swapped = Falsefor j in range(1, len(nums) - i):if nums[j] < nums[j - 1]:nums[j], nums[j - 1] = nums[j - 1], nums[j]swapped = Trueif not swapped:breakreturn nums
注意两个点: 1.用最外层的for loop代表最后n个数字已经完成了排序 2. 用swap变量来提前终止循环
merge sort
def merge_sort(nums):if len(nums) <= 1:return numsmid = len(nums) // 2# 分left = merge_sort(nums[:mid])right = merge_sort(nums[mid:])# 合并return merge(left, right)def merge(left, right):res = []i = 0j = 0while i < len(left) and j < len(right):if left[i] <= right[j]:res.append(left[i])i += 1else:res.append(right[j])j += 1res += left[i:]res += right[j:]return res
注意不要忘记了base case哦
快速排序 (注意下partition那一步是怎么写的)
def quick_sort(nums):n = len(nums)def quick(left, right):if left >= right:return numspivot = lefti = leftj = rightwhile i < j:while i < j and nums[j] >= nums[pivot]:j -= 1while i < j and nums[i] <= nums[pivot]:i += 1nums[i], nums[j] = nums[j], nums[i]nums[pivot], nums[j] = nums[j], nums[pivot]quick(left, j - 1)quick(j + 1, right)return numsreturn quick(0, n - 1)
一定要注意是先变化j, 因为我们的pivot是从index 0 选的, 就应该从对面开始
215 数组中第k大的元素
就是quick_select