选择排序
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 -= 1
return nums
注意使用里面的while loop来实现一直交换的效果
冒泡排序
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
swapped = False
for j in range(1, len(nums) - i):
if nums[j] < nums[j - 1]:
nums[j], nums[j - 1] = nums[j - 1], nums[j]
swapped = True
if not swapped:
break
return nums
注意两个点: 1.用最外层的for loop代表最后n个数字已经完成了排序 2. 用swap变量来提前终止循环
merge sort
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
# 分
left = merge_sort(nums[:mid])
right = merge_sort(nums[mid:])
# 合并
return merge(left, right)
def merge(left, right):
res = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
res.append(left[i])
i += 1
else:
res.append(right[j])
j += 1
res += 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 nums
pivot = left
i = left
j = right
while i < j:
while i < j and nums[j] >= nums[pivot]:
j -= 1
while i < j and nums[i] <= nums[pivot]:
i += 1
nums[i], nums[j] = nums[j], nums[i]
nums[pivot], nums[j] = nums[j], nums[pivot]
quick(left, j - 1)
quick(j + 1, right)
return nums
return quick(0, n - 1)
一定要注意是先变化j, 因为我们的pivot是从index 0 选的, 就应该从对面开始
215 数组中第k大的元素
就是quick_select