import random
lis=list(range(100))
random.shuffle(lis)print(lis)
冒泡排序
def bubbleSort(arr):for i inrange(1,len(arr)):for j inrange(0,len(arr)-i):if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]return arr
print(bubbleSort(lis))
选择排序
def selectionSort(arr):for i inrange(len(arr)):
temp=i
for j inrange(i,len(arr)-1):if arr[temp]>arr[j]:
temp=j
arr[i],arr[temp]=arr[temp],arr[i]return arr
print(selectionSort(lis))
插入排序
def insertionSort(arr):for i inrange(1,len(arr)):for j inrange(0,i):if arr[i]<arr[j]:for k inrange(j,i):
arr[k],arr[i]=arr[i],arr[k]return arr
print(insertionSort(lis))
希尔排序
import math
def shellSort(arr):
gap=1while(gap <len(arr)/3):
gap = gap*3+1while gap >0:for i inrange(gap,len(arr)):
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 = math.floor(gap/3)return arr
print(shellSort(lis))
归并排序递归
#递归
def mergeSort(arr):
n =len(arr)if n <=1:return arr
n = n//2
sub1 =mergeSort(arr[:n])
sub2 =mergeSort(arr[n:])returnmerge(sub1, sub2)
#合并两个有序数组
def merge(sub1, sub2):
n1 =len(sub1)
n2 =len(sub2)
i =0
j =0
merge =[]while i < n1 and j < n2:if sub1[i]< sub2[j]:
merge.append(sub1[i])
i +=1else:
merge.append(sub2[j])
j +=1
# 没复制完的
while i < n1:
merge.append(sub1[i])
i +=1while j < n2:
merge.append(sub2[j])
j +=1return merge
print(mergeSort(lis))
归并排序迭代
def MergeSort(arr):
n =len(arr)
size =1 # 表示每一步要归并的数组的长度
m =[]while size <= n:for i inrange(0, n-size, size+size):
m =merge(arr[i: i+size], arr[i+size:min(i+size+size, n)]) # min(i+size+size, n)为了最后一组数组可能不够全
arr[i:min(i+size+size, n)]= m[:] # 把merge得到的结果赋值给原始数组
size += size # 数组长度每次乘二
return m
#合并两个有序数组
def merge(sub1, sub2):
n1 =len(sub1)
n2 =len(sub2)
i =0
j =0
merge =[]while i < n1 and j < n2:if sub1[i]< sub2[j]:
merge.append(sub1[i])
i +=1else:
merge.append(sub2[j])
j +=1
# 没复制完的
while i < n1:
merge.append(sub1[i])
i +=1while j < n2:
merge.append(sub2[j])
j +=1return merge
print(MergeSort(lis))
快速排序
def quickSort(arr):returnhelpQs(arr,0,len(arr)-1)
def helpQs(arr,left,right):if left>right:return
k=arr[left]
i=left
j=right
while i!=j:while arr[j]>k and i<j:
j-=1while arr[i]<=k and i<j:
i+=1if i<j:
arr[i],arr[j]=arr[j],arr[i]
arr[left],arr[i]=arr[i],arr[left]helpQs(arr,left,i-1)helpQs(arr,i+1,right)return arr
print(quickSort(lis))