wiki几类排序算法原理后,写起来就不费劲了,有瑕疵,还请见谅。
-
#冒泡排序
-
def bulle_sort(so,so_1):
-
for i in range(so_1):
-
int (i)
-
if so[i:i+1]>so[i+1:i+2]:
-
temp=so[i+1:i+2]
-
so[i+1:i+2]=so[i:i+1]
-
so[i:i+1]=temp
-
so_1=len(so)-1
-
return (bulle_sort(so,so_1)) #递归函数
-
#直接插入排序
-
def Insert_sort(so):
-
ss=[]
-
for i in range(len(so)-1):
-
ss=so[i:i+1]
-
if so[i:i+1]<so[i+1:i+2]:
-
ss=ss.extend(so[i+1:i+2])
-
else:
-
soi=so[i+1:i+2]
-
ss=soi.extend(ss[i:i+1])
-
so=ss
-
return (so)
-
#直接选择排序
-
def Select_sort(so,n):
-
mi=[]
-
small=0
-
for i in range(0,n):
-
small=i
-
j=i+1
-
for j in range(j,n):
-
if so[j]<so[small]:
-
small=j
-
if small!=i:
-
mi=so[i]
-
so[i]=so[small]
-
so[small]=mi
-
return (so)
-
#堆排序
-
def Heap_sort(so):
-
def Create_heap(start,end):
-
root=start
-
-
while True:
-
child=(2*root+1)
-
if child > end:
-
break
-
if (child+1)<=end and so[child]<so[child+1]:
-
child+=1
-
if so[root]<so[child]:
-
so[root],so[child]=so[child],so[root]
-
root=child
-
else:
-
break
-
for i in range(int ((len(so)-2)/2),-1,-1):
-
Create_heap(i,len(so)-1)
-
for n in range(len(so)-1,0,-1):
-
so[0],so[n]=so[n],so[0]
-
Create_heap(0,n-1)
-
return (so)
-
#快速排序
-
def Quick_sort(so,low,high):
-
tmp=so[low]
-
i=low
-
j=high
-
while i<j:
-
while i<j and so[j]>=tmp:
-
j=j-1
-
if i<j:
-
so[i]=so[j]
-
i=i+1
-
while i<j and so[i]<tmp:
-
i=i+1
-
if i<j:
-
so[j]=so[i]
-
j=j-1
-
so[i]=tmp
-
if low<i:
-
Quick_sort(so,low,i-1)
-
if i<high:
-
Quick_sort(so,j+1,high)
-
-
-
if __name__=='__main__':
-
so=[3,4,33,7,9,3,10,2,88]
-
so_1=len(so)
-
-
bulle_sort(so,so_1)
-
print ("Bulle sort:")
-
print (so)
-
-
Insert_sort(so)
-
print ("Insert sort:")
-
print (so)
-
-
Select_sort(so,so_1)
-
print ("Select sort:")
-
print (so)
-
-
Heap_sort(so)
-
print ("Heap sort:")
-
print (so)
-
-
Quick_sort(so,0,(len(so)-1))
-
print ("Quick sort:")
-
print (so)
阅读(1482) | 评论(0) | 转发(0) |