常見排序演算法Python實現

2021-09-20 18:32:56 字數 2940 閱讀 1112

氣泡排序:

最優時間複雜度: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], alist[i+1] = alist[i+1], alist[i]

count += 1

if count == 0:

break

return alist

選擇排序:

最優時間複雜度:o(n^2)

最壞時間複雜度:o(n^2)

穩定性:不穩定

def choose_sort(alist):

"""選擇排序"""

for i in range(len(alist)):

min_x = alist[i]

min_pos = i

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

if alist[j] < min_x:

min_x = alist[j]

min_pos = j

alist[min_pos], alist[i] = alist[i], alist[min_pos]

return alist

插入排序:

最優時間複雜度:o(n)

最壞時間複雜度:o(n^2)

穩定性:穩定

def insert_sort(alist):

"""插入排序"""

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

for i in range(j, 0, -1):

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

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

else:

break

return alist

希爾排序:

最優時間複雜度:根據步長而調整

最壞時間複雜度:o(n^2)

穩定性:不穩定

def shell_sort(alist):

"""希爾排序"""

gap = len(alist) // 2

#gap到0之前,插入演算法執行的次數

while gap >= 1:

#插入演算法,與普通插入演算法區別在於gap步長

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

i = j

while i > 0:

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

alist[i], alist[i-gap] = alist[i-gap], alist[i]

i -= gap

else:

break

#調整步長

gap = gap // 2

return alist

快速排序:

最優時間複雜度:o(nlogn)

最壞時間複雜度:o(n^2)

穩定性:不穩定

def quick_sort(alist, first, last):

"""快速排序"""

if first >= last:

return

low = first

high = last

mid = alist[low]

while low < high:

#high 左移

while low < high and alist[high] >= mid:

high -= 1

alist[low] = alist[high]

#low 右移

while low < high and alist[low] < mid:

low += 1

alist[high] = alist[low]

alist[low] = mid

quick_sort(alist, first, low-1)

quick_sort(alist, low+1, last)

歸併排序:

最優時間複雜度:o(nlogn)

最壞時間複雜度:o(nlogn) 

穩定性:穩定

def merge_sort(alist):

"""歸併排序"""

n = len(alist)

if n == 1:

return alist

mid = n // 2

left_li = merge_sort(alist[:mid])

right_li = merge_sort(alist[mid:])

left_pointer, right_pointer = 0, 0

result =

while left_pointer if left_li[left_pointer] < right_li[right_pointer]:

left_pointer += 1

else:

right_pointer += 1

result += left_li[left_pointer:]

result += right_li[right_pointer:]

return result

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實現

穩定性是指序列中相同的數字在排序後相對位置不發生改變 常見的且穩定的排序演算法有冒泡 歸併 插入,其餘的為非穩定的排序演算法 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...