1. 程式人生 > >八大排序演算法(python)

八大排序演算法(python)

class Solution():
def insert_sort(self,lists):#插入排序
count=len(lists)
for i in range(1,count):
key=lists[i]
j=i-1
while j>=0:
if lists[j]>key:
lists[j+1]=lists[j]
lists[j]=key
j=j-1
print(lists)


def shell_sort(self,lists):#希爾排序
count=len(lists)
step=count//2
while step>0:
for i in range(step,count):
while i>step and lists[i-step]>lists[i]:
lists[i],lists[i-step]=lists[i-step],lists[i]
i=i-step
step=step//2
print(lists)


def bubble_sort(self,lists):#氣泡排序
for i in range(0,len(lists)-1):
for j in range(i,len(lists)):
if lists[i]>lists[j]:
lists[i],lists[j]=lists[j],lists[i]
print(lists)


def select_sort(self,lists):#直接選擇排序
for i in range(len(lists)):
min=i
j=i+1
while j<len(lists):
if lists[j]<lists[min]:
min=j
j=j+1
lists[i],lists[min]=lists[min],lists[i]
print(lists)


def max_heap(self,lists,listsize,root):
left=2*root+1
right=left+1
larger=root
if left<listsize and lists[left]>lists[larger]:
larger=left
if right<listsize and lists[right]>lists[larger]:
larger=right
if larger!=root:
lists[larger],lists[root]=lists[root],lists[larger]
self.max_heap(lists,listsize,larger)
def build_maxheap(self,lists):
listsize=len(lists)
for i in range((listsize-2//2),-1,-1):
self.max_heap(lists,listsize,i)
def heap_sort(self,lists):#堆排序 
heapsize=len(lists)
self.build_maxheap(lists)
for i in range((heapsize-1),-1,-1):
lists[0],lists[i]=lists[i],lists[0]
self.max_heap(lists,i,0)
print(lists)


def merge(self,left,right):
leftsize=len(left)
rightsize=len(right)
i,j=0,0
result=[]
while i<leftsize and j<rightsize:
if left[i]<right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
result=result+left[i:]
result=result+right[j:]
return result
def merge_sort(self,lists):
if len(lists)<=1:
return lists
mid=len(lists)//2
left=self.merge_sort(lists[:mid])
right=self.merge_sort(lists[mid:])
return self.merge(left,right)


from random import randint
def radix_sort(self,lists,d):#基數排序
for k in range(d):
s=[[]for i in range(10)]
for i in lists:
s[i//(10**k)%10].append(i)
lists=[j for i in s for j in i]
print (lists)


def quick_sort(self,lists):
listsize=len(lists)
if listsize<=1:
return lists
flag=lists[listsize-1]
i=0
j=listsize-2
iflag=jflag=False
while i<=j :
if lists[i]<flag:
i=i+1
iflag=False
else:
iflag=True
if lists[j]>flag:
j=j-1
jflag=False
else:
jflag=True
if iflag and jflag:
lists[i],lists[j]=lists[j],lists[i]


lists[i],lists[listsize-1]=lists[listsize-1],lists[i]

return self.quick_sort(lists[:i])+[lists[i]]+self.quick_sort(lists[i+1:])





if __name__ == '__main__':
a=[5,4,2,1,13,7,65,32]
#Solution().insert_sort(a)
#Solution().shell_sort(a)
#Solution().bubble_sort(a)
#Solution().select_sort(a)
#Solution().heap_sort(a)
#Solution().merge_sort(a)
#print(a)
#Solution().radix_sort(a,3)
b=[2]

print(Solution().quick_sort(a))