# 快排defsortArray(self, nums: List[int])-> List[int]:defpartition(start, end, nums):
flag = start -1for k inrange(start, end):if nums[k]< nums[end]:
flag +=1
nums[flag], nums[k]= nums[k], nums[flag]
nums[flag+1], nums[end]= nums[end], nums[flag+1]return flag+1defquick_sort(i, j, nums):if i >= j:return
index = partition(i, j, nums)
quick_sort(i, index-1, nums)
quick_sort(index+1, j, nums)
quick_sort(0,len(nums)-1, nums)return nums
堆排序
# 堆排序defsortArray(self, nums: List[int])-> List[int]:defmax_heapify(heap, size, root):# 默认左右子树都是调整好的堆,现在调整根节点
left = root *2+1
right = root *2+2
larger = root
if left < size and heap[left]> heap[larger]:
larger = left
if right < size and heap[right]> heap[larger]:
larger = right
if larger != root:
heap[larger], heap[root]= heap[root], heap[larger]
max_heapify(heap, size, larger)defbuild_heap(heap):# 建堆
size =len(heap)
start = size //2-1for i inrange(start,-1,-1):# print(i)
max_heapify(heap, size, i)defheap_sort(nums):# 堆排序
build_heap(nums)for i inrange(len(nums)-1,-1,-1):
nums[0], nums[i]= nums[i], nums[0]
max_heapify(nums, i,0)
heap_sort(nums)return nums
归并排序
# 归并排序defsortArray(self, nums: List[int])-> List[int]:defmerge(nums1, nums2):
res =[]
i =0
j =0while i <len(nums1)and j <len(nums2):if nums1[i]<= nums2[j]:
res.append(nums1[i])
i +=1else:
res.append(nums2[j])
j +=1if i <len(nums1):for k inrange(i,len(nums1)):
res.append(nums1[k])if j <len(nums2):for k inrange(j,len(nums2)):
res.append(nums2[k])return res
defmergesort(nums):iflen(nums)<=1:return nums
mid =len(nums)//2
left = mergesort(nums[:mid])
right = mergesort(nums[mid:])return merge(left, right)return mergesort(nums)
冒泡排序
# 冒泡排序defsortArray(self, nums: List[int])-> List[int]:for i inrange(len(nums)):# 控制循环次数
flag =Truefor j inrange(1,len(nums)-i):# 冒泡if nums[j]< nums[j-1]:
nums[j], nums[j-1]= nums[j-1], nums[j]
flag =Falseprint(nums)if flag:return nums
return nums