数据结构与算法篇——排序

1、冒泡

def maopao_sort(list_):
for i in range(len(list_)-1):
for j in range(i+1,len(list_)):
if list_[j]<list_[i]:
list_[i],list_[j]=list_[j],list_[i]
return list_
def gaijin_maopao(list_):
for i in range(1,len(list_)):
flag=False
for j in range(len(list_)-i):
if list_[j]>list_[j+1]:
list_j,list_[j+1]=list_[j+1],list_[j]
flag=True
if not flag:
break

2、插入

def insertsort(s):
for i in range(1,len(s)):
tem=s[i]
j=i-1
while j>=0 and s[j]>tem:
s[j+1],tem=tem,s[j]
j-=1
return s

3、快排

def quick_sort(list_):
if len(list_)<=1:
return list_
else:
a=list_[0]
left=[i for i in list_[1:] if i<=a]
right=[j for j in list_[1:] if j>a]
return quick_sort(left)+[a]+quick_sort(right)

4、选择

def select_sort(list_):
for i in range(len(list_)-1):
min_=i
for j in range(i+1,len(list_)):
if list_[j]<list_[min_]:
min_=j
list_[min_],list_[i]=list_[i],list_[min_]
return list_

5、堆排序

from heapq import heappush,heappop
def heapsort(list_):
h=[]
for value in list_:
heappush(h,value)
return [heappop(h) for i in range(len(h))]

6、归并

def mergesort(list_):
mid=len(list_)//2
left,right=list_[:mid],list_[mid:]
if len(left)>1:
left=mergesort(left)
if len(right)>1:
right=mergesort(right)
res=[]
while left and right:
if left[-1]>right[-1]:
res.append(left.pop())
else:
res.append(right.pop())
res.reverse()
return (left or right) +res