python 實現常見排序演算法

2021-09-12 10:28:00 字數 3289 閱讀 5655

#coding:utf-8

#bubble sort (氣泡排序),時間複雜度最壞為o(n2),最優的為n

import time

def bubble_sort(alist):

'''氣泡排序

:param alist:

:return:

'''cur = 1

while cur != len(alist)-1 and len(alist) != 1:

for i in range(len(alist)-cur):

if alist[i] > alist[i+1]:

alist[i], alist[i+1] = alist[i+1], alist[i]

cur += 1

print(alist)

def bubble_sort2(alist):

for j in range(len(alist)-1):

for i in range(len(alist)-1-j):

if alist[i] > alist[i+1]:

alist[i],alist[i+1] = alist[i+1],alist[i]

print(alist)

if __name__ == "__main__":

alist = [1,2,9,6,35,77,7,8]

alist1 = [2]

bubble_sort2(alist1)

##select sort 選擇排序 ,時間複雜最優n^2,最壞也為n^2

def select_sort(alist):

for j in range(len(alist)-1):

min_index = j

for i in range(1+j,len(alist)):

if alist[min_index] > alist[i]:

min_index = i

alist[min_index],alist[j] = alist[j],alist[min_index]

return alist

if __name__ == "__main__":

alist = [3,4,5,8,1,0,23]

# print(select_sort(alist))

###插入排序

def insert_sort(alist):

for j in range(1,len(alist)):

i = j

while i>0:

if alist[i]>alist[i-1]:

alist[i],alist[i-1] = alist[i-1],alist[i]

i -= 1

else:

break

return alist

if __name__ == "__main__":

alist = [3,4,5,8,1,0,23]

# print(insert_sort(alist))

##希爾排序 , 插入排序的優化

def shell_sort(alist):

n = len(alist)

gap = n//2

for i in range(gap,len(alist)):

j = i

for k in range(i,0,-gap):

if alist[k] < alist[k-gap]:

alist[k], alist[k-gap] = alist[k-gap], alist[k]

print(alist)

if __name__ == "__main__":

alist = [3,4,5,8,1,0,23]

# shell_sort(alist)

##快速排序,時間複雜度,最優的時間複雜度為o(logn),最壞時間複雜度為o(n^2)

def quick_sort(alist,first,last):

if first < last:

start = first

end = last

base = alist[start]

while start =alist[start]):

start += 1

alist[end] = alist[start]

alist[start] = base

quick_sort(alist,first,start-1)

quick_sort(alist,start+1,last)

return alist

if __name__ == "__main__":

alist = [3,4,5,8,1,0,0,23]

# print("result:"+str(quick_sort(alist,0,len(alist)-1)))

#歸併演算法,時間複雜度nlogn,此演算法返回的是乙個新列表

def merge_sort(alist):

"""歸併演算法的基本實現

:param alist:列表

:return:排序後的列表

"""lens = len(alist)

if lens <= 1:

return alist

mid = lens//2

#left 採用歸併排序

常見排序演算法Python實現

氣泡排序 最優時間複雜度 o n 最壞時間複雜度 o n 2 穩定性 穩定 def bubble sort alist 氣泡排序 for j in range len alist 1,0,1 count 0 for i in range j if alist i alist i 1 alist i ...

常見排序演算法 python實現

穩定性是指序列中相同的數字在排序後相對位置不發生改變 常見的且穩定的排序演算法有冒泡 歸併 插入,其餘的為非穩定的排序演算法 def bubble sort alist for j in range len alist 1 0,1 for i in range j if alist i alist ...

常見排序演算法的python實現

氣泡排序和選擇排序 defbubblesort alist for i in range len alist 1 0,1 for j in range i if alist j alist j 1 alist j alist j 1 alist j 1 alist j return alist al...