常見排序演算法 python實現

2021-10-24 15:40:28 字數 3496 閱讀 2104

穩定性是指序列中相同的數字在排序後相對位置不發生改變

常見的且穩定的排序演算法有冒泡、歸併、插入,其餘的為非穩定的排序演算法

def bubble_sort

(alist)

:for j in

range

(len

(alist)-1

,0,-

1):for i in

range

(j):

if alist[i]

>alist[i+1]

: alist[i]

,alist[i+1]

= alist[i+1]

,alist[i]

li =[54

,26,93

,17,77

,31,44

,55,20

]bubble_sort

(li)

print

(li)

def merge_sort

(alist)

: n =

len(alist)

if n <=1:

return alist

num = n //2

left =

merge_sort

(alist[

:num]

) right =

merge_sort

(alist[num:])

return

merge

(left,right)

def merge

(left,right)

: l,r =0,

0 res =

while l <

len(left) and r <

len(right)

:if left[l]

< right[r]

: res.

(left[l]

) l+=

1else

: res.

(right[r]

) r+=

1 res+=left[l:

] res+=right[r:

]return res

alist =[54

,26,93

,17,77

,31,44

,55,20

]sorted_alist =

merge_sort

(alist)

print

(sorted_alist)

插入排序 簡單記做 『在有序的序列中插入值』

def insert_sort

(alist)

: n =

len(alist)

for i in

range(1

,n):

for j in

range

(i,0,-

1):if alist[j]

: alist[j]

,alist[j-1]

= alist[j-1]

,alist[j]

alist =[54

,26,93

,17,77

,31,44

,55,20

]insert_sort

(alist)

print

(alist)

一種改進的插入排序

def shell_sort

(alist)

: n =

len(alist)

gap = n //2

while gap >0:

for i in

range

(gap,n)

: j = i

while j >= gap and alist[j-gap]

> alist[j]

: alist[j]

,alist[j-gap]

= alist[j-gap]

,alist[j]

j-=gap

gap= gap//2

alist =[54

,26,93

,17,77

,31,44

,55,20

]shell_sort

(alist)

print

(alist)

在未排序中搜尋到最值放在序列起始位置

def select_sort

(alist)

: n =

len(alist)

for i in

range

(n-1):

minindex = i

for j in

range

(i+1

,n):

if alist[j]

: minindex = j

if minindex != i:

alist[minindex]

,alist[i]

= alist[i]

,alist[minindex]

li =[54

,26,93

,17,77

,31,44

,55,20

]select_sort

(li)

print

(li)

def quick

(alist)

: n =

len(alist)

if n <2:

return alist

else

: base = alist[0]

left =

[i for i in alist[1:

]if alist[i]

right =

[i for i in alist[1:

]if alist[i]

>base]

return left +

[base]

+ right

alist =[54

,26,93

,17,77

,31,44

,55,20

]alist1 =

quick_sort

(alist)

print

(alist1)

python 實現常見排序演算法

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...

常見排序演算法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實現

氣泡排序和選擇排序 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...