defmergeSort(nums):defmerge(left, right):
res =[]
i =0
j =0while i<len(left)and j<len(right):if left[i]<=right[j]:
res.append(left[i])
i +=1else:
res.append(right[j])
j +=1return res + left[i:]+ right[j:]iflen(nums)<=1:#必须加这个,否则如果length=1会死循环return nums
mid =len(nums)//2
left = mergeSort(nums[:mid])
right = mergeSort(nums[mid:])return merge(left, right)
6、快速排序
defquickSort(nums, left, right):defpartion(nums, left, right):
tmp = nums[left]while left<right:while left<right and nums[right]>=tmp:
right -=1
nums[left]= nums[right]while left<right and nums[left]<=tmp:
left +=1
nums[right]= nums[left]
nums[right]= tmp
return left
if left<right:
base = partion(nums, left, right)
quickSort(nums, left, base-1)
quickSort(nums, base+1, right)return nums
7、堆排序
defheapSort(nums):# 用大根堆(当前节点值>=子节点值),做升序排序defadjustHeap(nums, i, length):# 非叶子节点的左、右孩子
left =2* i +1
right =2* i +2# 找到当前节点与两个孩子中的最大值
largest = i
if left<length and nums[left]>nums[largest]:
largest = left
if right<length and nums[right]>nums[largest]:
largest = right
# 如果最大值不是当前节点,交换,继续调整堆if largest!=i:
nums[largest], nums[i]= nums[i], nums[largest]
adjustHeap(nums, largest, length)for i inrange(len(nums)//2-1,-1,-1):#建立堆,从最后一个非叶子节点开始
adjustHeap(nums, i,len(nums))for i inrange(len(nums)-1,-1,-1):#排序,每次取最大数(根节点),然后调整堆
nums[i], nums[0]= nums[0], nums[i]
adjustHeap(nums,0, i)return nums
8、计数排序
defcountSort(nums):
bucket =[0]*(max(nums)-min(nums)+1)for n in nums:
bucket[n-min(nums)]+=1
i =0for j inrange(len(bucket)):while bucket[j]>0:
nums[i]= j +min(nums)
bucket[j]-=1
i +=1return nums
9、桶排序
defbucketSort(nums, bucketSize =2):
bucketCount =(max(nums)-min(nums))// bucketSize +1#数据分为bucketCount组
buckets =[]# 二维桶for i inrange(bucketCount):
buckets.append([])# 利用函数映射将各个数据放入对应的桶中for num in nums:
buckets[(num -min(nums))// bucketSize].append(num)
nums.clear()# 清空 nums# 对每一个二维桶中的元素进行排序for bucket in buckets:
insertionSort(bucket)# 假设使用插入排序
nums.extend(bucket)# 将排序好的桶依次放入到 nums 中return nums
10、基数排序
defradixSort(nums):
mod =10
div =1
mostBit =len(str(max(nums)))# 最大数的位数决定了外循环多少次
buckets =[[]for row inrange(mod)]# 构造 mod 个空桶while mostBit:for num in nums:# 将数据放入对应的桶中
buckets[num // div % mod].append(num)
i =0# nums 的索引for bucket in buckets:# 将数据收集起来while bucket:
nums[i]= bucket.pop(0)# 依次取出
i +=1
div *=10
mostBit -=1return nums