1.冒泡排序算法
def bubblesort(data):
n=len(data)
for i in range(0,n):
for j in range(i+1,n):
if data[i]>data[j]:
data[i],data[j]=data[j],data[i]
return data
if __name__ == '__main__':
a=[58,47,69,20,15,66,52,80,30,64]
print(bubblesort(a))
def bubblesort(target):
length=len(target)
while length>0:
length-=1
cur=0
while cur<length:
if target[cur]>target[cur+1]:
target[cur],target[cur+1]=target[cur+1],target[cur]
cur+=1
return target
if __name__ == '__main__':
a=[58,47,69,20,15,66,52,80,30,64]
print(bubblesort(a))
2.快速排序算法
def quicksort(data):
if len(data) >= 2:
mid = data[len(data)//2]
left, right = [], []
data.remove(mid)
for num in data:
if num >= mid:
right.append(num)
else:
left.append(num)
return quicksort(left) + [mid] + quicksort(right)
else:
return data
if __name__ == '__main__':
array = [2,3,5,7,1,4,6,15,5,2,7,9,10,15,9,17,12]
print(quicksort(array))
3.选择排序算法
def selectsort(data):
length=len(data)
for i in range(0,length):
min=i
for j in range(i+1,length):
if data[min]>data[j]:
min=j
data[min],data[i]=data[i],data[min]
return data
if __name__=='__main__':
a=[58,47,69,20,15,66,52,80,30,64]
print(selectsort(a))
4.堆排序算法
def adjust(list,i,length):
lchild=2*i+1
rchild=2*i+1
max=i
if i<length/2:
if lchild<length and list[lchild]>list[max]:
max=lchild
if rchild<length and list[rchild]>list[max]:
max=rchild
if max!=i:
list[max],list[i]=list[i],list[max]
adjust(list,max,length)
def create(list,length):
for i in range(0,(int(length/2)))[::-1]:
adjust(list,i,length)
def sort(list):
length=len(list)
create(list,length)
for i in range(0,length)[::-1]:
list[0],list[i]=list[i],list[0]
adjust(list,0,i)
return list
if __name__ == '__main__':
a=[58,47,69,20,15,66,52,80,30,64]
print(sort(a))
5.插入排序算法
def insertsort(list):
length=len(list)
for i in range(1,length):
temp=list[i]
j=i-1
while j>=0:
if list[j]>temp:
list[j+1]=list[j]
list[j]=temp
j-=1
return list
if __name__ == '__main__':
a=[58,47,69,20,15,66,52,80,30,64]
print(insertsort(a))
6.希尔排序算法
def shellsort(list):
length=len(list)
gap=length//2
while gap>=1:
for i in range(gap,length):
while i>=gap and list[i-gap]>list[i]:
list[i-gap],list[i]=list[i],list[i-gap]
i-=gap
gap//=2
a=[58,47,69,20,15,66,52,80,30,64]
shellsort(a)
print(a)
|