1.快速排序
import time
def cal_time(func):
def inner(*args,**kwargs):
time1 = time.time()
func(*args,**kwargs)
time2 = time.time()
print('this is consume %s miao'%(time2-time1))
return inner
def paration(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
def quick_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.归并排序
def merge(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 += 1
else:
ltmp.append(li[j])
while i <= mid:
ltmp.append(li[i])
i += 1
while j <= high:
ltmp.append(li[j])
j += 1
li[low:high+1] = ltmp
#一次归并
def merge_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.冒泡排序
def bubble_sort(li):
n = len(li)
for i in range(n - 1): #i表示的趟数
for j in range(0,n-i-1): #下标的箭头
if li[j] > li[j+1]:
li[j],li[j+1] = li[j+1],li[j]
4.插入排序
def insert_sort(li):
n = len(li)
for i in range(1,n):
tmp = li[i]
j = i - 1
while j >= 0 and li[j] > tmp:
li[j+1] = li[j]
print(j)
j -= 1
li[j+1] = tmp
5.选择排序
def select_sort(li):
n = len(li)
for i in range(0,n-1):
min_pas = i
for j in range(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.桶排序
def bin_sort(li,min_num=0,max_num=99,bin_num=8):
bin = [[] for i in range(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 - 1
while j >= 0 and temp < li[j]:
li[j+1] = li[j]
j = j - 1
li[j+1] = temp
res = []
print(bin)
for l in bin:
res.extend(l)
return res
import random
li = [random.randint(0,99) for i in range(100)]
print(bin_sort(li))
来源:CSDN
作者:小爬虫@bxy
链接:https://blog.csdn.net/qq_42992704/article/details/104790298