defmerge_sort(arr):iflen(arr)>1:
mid =len(arr)//2# 找到数组的中间点
L = arr[:mid]# 将数组分成两部分
R = arr[mid:]
merge_sort(L)# 递归排序左半部分
merge_sort(R)# 递归排序右半部分
i = j = k =0# 合并两个已排序的子数组while i <len(L)and j <len(R):if L[i]< R[j]:
arr[k]= L[i]
i +=1else:
arr[k]= R[j]
j +=1
k +=1# 检查是否还有剩余的元素while i <len(L):
arr[k]= L[i]
i +=1
k +=1while j <len(R):
arr[k]= R[j]
j +=1
k +=1return arr
5. 快速排序 (Quick Sort)
defquick_sort(arr):iflen(arr)<=1:return arr
pivot = arr[len(arr)//2]# 选择数组的中间元素作为基准
left =[x for x in arr if x < pivot]# 所有小于基准的元素
middle =[x for x in arr if x == pivot]# 所有等于基准的元素
right =[x for x in arr if x > pivot]# 所有大于基准的元素return quick_sort(left)+ middle + quick_sort(right)
6. 堆排序 (Heap Sort)
defheapify(arr, n, i):
largest = i # 假设当前节点是最大值
l =2* i +1# 左子节点
r =2* i +2# 右子节点# 如果左子节点存在且大于当前节点if l < n and arr[i]< arr[l]:
largest = l
# 如果右子节点存在且大于当前最大值if r < n and arr[largest]< arr[r]:
largest = r
# 如果最大值不是当前节点if largest != i:
arr[i], arr[largest]= arr[largest], arr[i]# 交换
heapify(arr, n, largest)# 递归堆化受影响的子树defheap_sort(arr):
n =len(arr)# 构建最大堆for i inrange(n //2-1,-1,-1):
heapify(arr, n, i)# 一个个提取元素for i inrange(n -1,0,-1):
arr[i], arr[0]= arr[0], arr[i]# 交换
heapify(arr, i,0)return arr
7. 希尔排序 (Shell Sort)
defshell_sort(arr):
n =len(arr)
gap = n //2while gap >0:for i inrange(gap, n):
temp = arr[i]
j = i
# 插入排序while j >= gap and arr[j - gap]> temp:
arr[j]= arr[j - gap]
j -= gap
arr[j]= temp
gap //=2return arr
8. 计数排序 (Counting Sort)
defcounting_sort(arr):
max_val =max(arr)
m = max_val +1
count =[0]* m
# 统计每个元素的个数for a in arr:
count[a]+=1
i =0for a inrange(m):for c inrange(count[a]):
arr[i]= a
i +=1return arr
9. 基数排序 (Radix Sort)
defcounting_sort_for_radix(arr, exp):
n =len(arr)
output =[0]* n
count =[0]*10# 统计每个基数的个数for i inrange(n):
index = arr[i]// exp
count[index %10]+=1for i inrange(1,10):
count[i]+= count[i -1]
i = n -1while i >=0:
index = arr[i]// exp
output[count[index %10]-1]= arr[i]
count[index %10]-=1
i -=1for i inrange(n):
arr[i]= output[i]defradix_sort(arr):
max_val =max(arr)
exp =1while max_val // exp >0:
counting_sort_for_radix(arr, exp)
exp *=10return arr
10. 桶排序 (Bucket Sort)
defbucket_sort(arr):iflen(arr)==0:return arr
bucket =[]
slot_num =10# 桶的数量for i inrange(slot_num):
bucket.append([])# 将元素分配到不同的桶中for j in arr:
index =int(slot_num * j)
bucket[index].append(j)# 对每个桶中的元素进行排序for i inrange(slot_num):
bucket[i]= insertion_sort(bucket[i])
k =0for i inrange(slot_num):for j inrange(len(bucket[i])):
arr[k]= bucket[i][j]
k +=1return arr
11. Tim Sort (Tim Sort)
MIN_MERGE =32defcalc_min_run(n):
r =0while n >= MIN_MERGE:
r |= n &1
n >>=1return n + r
definsertion_sort_for_timsort(arr, left, right):for i inrange(left +1, right +1):
temp = arr[i]
j = i -1while j >= left and arr[j]> temp:
arr[j +1]= arr[j]
j -=1
arr[j +1]= temp
defmerge_for_timsort(arr, l, m, r):
len1, len2 = m - l +1, r - m
left, right =[],[]for i inrange(0, len1):
left.append(arr[l + i])for i inrange(0, len2):
right.append(arr[m +1+ i])
i, j,