1.冒泡排序
def bubble_sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
return arr
2.插入排序
def insert_sort(arr):
for i in range(1,len(arr)):
temp = arr[i]
j = i-1
while j>=0 and arr[j]>temp:
arr[j+1] = arr[j]
j+=1
arr[j+1] = temp
return arr
3.希尔排序(插入排序的升级版,因为对于基本有序且数据量少的数据用直接插入排序是很高效的,希尔排序就是将待排序序列分成多个子序列分别进行插入排序)
def shell_sort(arr):
size = len(arr)
gap = size//2
while gap>=1:
for i in range(gap,size):
temp = arr[i]
j = i-gap
while j>=0 and arr[j]>temp:
arr[j+gap] = arr[j]
j+=gap
arr[j+gap] = temp
gap//=2
return arr
4.选择排序
def select_sort(arr):
for i in range(len(arr)):
k = i
for j in range(i+1,len(arr)):
if arr[j]<arr[k]:
k = j
if k!=i:
arr[k],arr[i] = arr[i],arr[k]
return arr
5.归并排序
def merge(left,right):
res = []
i,j = 0,0
while i<len(left) and j<len(right):
if left[i]<=right[j]:
res.append(left.pop(0))
else:
res.append(right.pop(0))
res+=left if len(left) else right
return res
def merge_sort(arr):
if len(arr)==1:
return arr
mid = len(arr)//2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left,right)
6.快速排序
def quick_sort(arr,left,right):
if left>=right:
return arr
low = left
high = right
key = arr[low]
while left<right:
while left<right and arr[right]>key:
right-=1
arr[left] = arr[right]
left+=1
while left<right and arr[left]<=key:
left+=1
arr[right] = arr[left]
right-=1
arr[left] = key
quick_sort(arr,low,left-1)
quick_sort(arr,left+1,high)
return arr
7.计数排序
def counting_sort(arr):
max_num = max(arr)
index = 0
count_list = [0 for _ in range(max_num+1)]
for i in range(len(arr)):
count_list[arr[i]]+=1
for j in range(len(count_list)):
while count_list[j]>0:
arr[index] = j
index+=1
count_list[j]-=1
return arr
8.桶排序
def bucket_sort(arr):
min_num = min(arr)
max_num = max(arr)
bucket_range = (max_num-min_num)/len(arr)
bucket_list = [[] for _ in range(len(arr)+1)]
for i in arr:
bucket_list[int((i-min_num)//bucket_range))].append(i)
arr.clear()
for i in bucket_list:
for j in sorted(i):
arr.append(j)
return arr
9.基数排序
def radix_sort(arr):
i = 0
n =1
max_num = max(arr)
while max_num>10**n:
n+=1
while i<n:
bucket = {}
for x in range(10):
bucket[x] = []
for x in arr:
radix = (x//10**i)%10
bucket[radix].append(x)
j= 0
for x in range(10):
if len(bucket[x])!=0:
for k in bucket[x]:
arr[j].append(k)
j+=1
i+=1
return arr
10.堆排序
def max_heap(heap,heapsize,root):
left = 2*root+1
right = left+1
larger = root
if left<heapsize and heap[large]<heap[left]:
large = left
if right<heapsize and heap[large]<heap[right]:
large = right
if large!=root:
heap[large],heap[root] = heap[root],heap[large]
max_heap(heap,heapsize,large)
def buile_max_heap(heap):
heapsize = len(heap)
for i in range((heapsize-2)//2,-1,-1):
max_heap(heap,heap_size,i)
def heap_sort(heap):
build_max_heap(heap)
for i in range(len(heap)-1,-1,-1):
heap[0],heap[i] = heap[i],heap[0]
max_heap(heap,i,0)
return heap
over…