import time
defcal_time(func):definner(*args,**kwargs):
time1 = time.time()
func(*args,**kwargs)
time2 = time.time()print('this is consume %s miao'%(time2-time1))return inner
defparation(li,left,right):
tmp = li[left]while left < right:while left < right and li[right]>= tmp:
right -=1
li[left]= li[right]while left < right and li[left]<= tmp:
left +=1
li[right]= li[left]
li[left]= tmp
return left
def_quick_sort(li,left,right):if left < right:
mid = paration(li,left,right)
_quick_sort(li,left,mid-1)
_quick_sort(li,mid+1,right)
@cal_time
defquick_sort(li):return _quick_sort(li,0,len(li)-1)
li =list(range(10000,0,-1))import random
random.shuffle(li)
quick_sort(li)print(li)
2.归并排序
defmerge(li,low,mid,high):
i = low
j = mid +1
ltmp =[]while i <= mid and j <= high:if li[i]<= li[j]:
ltmp.append(li[i])
i +=1else:
ltmp.append(li[j])while i <= mid:
ltmp.append(li[i])
i +=1while j <= high:
ltmp.append(li[j])
j +=1
li[low:high+1]= ltmp
#一次归并defmerge_sort(li,low,high):if low < high:
mid =(low + high)//2
merge_sort(li,low,mid)
merge_sort(li,mid+1,high)
merge(li,low,mid,high)import random
li =list(range(1000))
random.shuffle(li)
merge_sort(li,0,len(li)-1)print(li)
3.冒泡排序
defbubble_sort(li):
n =len(li)for i inrange(n -1):#i表示的趟数for j inrange(0,n-i-1):#下标的箭头if li[j]> li[j+1]:
li[j],li[j+1]= li[j+1],li[j]
4.插入排序
definsert_sort(li):
n =len(li)for i inrange(1,n):
tmp = li[i]
j = i -1while j >=0and li[j]> tmp:
li[j+1]= li[j]print(j)
j -=1
li[j+1]= tmp
5.选择排序
defselect_sort(li):
n =len(li)for i inrange(0,n-1):
min_pas = i
for j inrange(i+1,n):if li[j]< li[min_pas]:
min_pas = j
if min_pas != i:
li[min_pas],li[i]= li[i],li[min_pas]
6.桶排序
defbin_sort(li,min_num=0,max_num=99,bin_num=8):bin=[[]for i inrange(bin_num)]for num in li:
n =(max_num-min_num+1)/ bin_num
#i=1 - 8 号桶 [(i-1)*n,i*n)bin[int(num // n)].append(num)#维护桶有序
li =bin[int(num // n)]
i =len(bin[int(num // n)])-1
temp = li[i]
j = i -1while j >=0and temp < li[j]:
li[j+1]= li[j]
j = j -1
li[j+1]= temp
res =[]print(bin)for l inbin:
res.extend(l)return res
import random
li =[random.randint(0,99)for i inrange(100)]print(bin_sort(li))