各種排序演算法的Python實現

2021-07-24 12:24:55 字數 2410 閱讀 2622

最近剛剛接觸python,python語法簡潔清晰,具有很好的易讀性,編寫的演算法可以很容易的看出其本質。故而用python編寫演算法,既可以熟悉演算法,又可以練習python,何樂而不為呢?

插入排序

def

insertsort

(lists):

for i in range(0, len(lists) - 1):

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

if lists[j] < lists[i]:

lists[i], lists[j] = lists[j], lists[i]

else:

break

選擇排序

def

selectionsort

(lists):

for i in range(0, len(lists)):

min_number = i

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

if lists[j] < lists[min_number]:

min_number = j

lists[i], lists[min_number] = lists[min_number], lists[i]# swap

歸併排序

def

mergesort

(lists):

if len(lists) <= 1:

return lists

num = int( len(lists)/2 )

return merge(mergesort(lists[:num]),

mergesort(lists[num:]))

defmerge

(left, right):

r, l = 0, 0

result =

while l < len(left) and r < len(right):

if left[l] < right[r]:

l += 1

else:

r += 1

result += right[r:]

result += left[l:]

return result

快速排序

def

quicksort

(lists, p, r):

if (p < r):

q = partition(lists, p, r)

quicksort(lists, p, q - 1)

quicksort(lists, q + 1, r)

defpartition

(lists, p, r):

x = lists[r]

i = p - 1

for j in range(p, r):

if (lists[j] <= x):

i += 1

lists[i], lists[j] = lists[j], lists[i]

lists[i + 1], lists[r] = lists[r], lists[i + 1]

return i + 1

堆排序

def

heapsort

(lists):

buildmaxheap(lists)

for i in range(len(lists) - 1, 0, -1):

lists[0], lists[i] = lists[i], lists[0]

maxheapify(lists, 0, i)

defbuildmaxheap

(lists):

for i in range((int)(len(lists) / 2) - 1, -1, -1):

maxheapify(lists, i, len(lists))

defmaxheapify

(lists, i, heap_size):

if2 * i + 1

< heap_size and lists[2 * i + 1] > lists[i]:

largest = 2 * i + 1

else:

largest = i

if2 * i + 2

< heap_size and lists[2 * i + 2] > lists[largest]:

largest = 2 * i + 2

if largest != i:

lists[i], lists[largest] = lists[largest], lists[i]

maxheapify(lists, largest, heap_size)

用Python實現各種排序演算法

比較相鄰的元素大小,將小的前移,大的後移,就像水中的氣泡一樣,最小的元素經過幾次移動,會最終浮到水面上。def bubble list for i in range len list for j in range 0,len list 1 i if list j list j 1 list j li...

各種排序演算法的實現

各種排序演算法的實現 1.快速排序 void swap int a,int b int partion int a,int p,int r a p a j a j x return j void quick sort int a,int p,int r a s rc heap adjust void...

各種排序演算法的實現

排序演算法在很多面試中都會涉及到,而且還分為很多種,看得眼花繚亂的,這兒我就先說說幾個較簡單的演算法的實現 本來是想把各種排序方法寫在乙個函式裡可供選擇使用的,但是想著還是把每種演算法直觀的說清楚最好,故分開實現。1 插入排序 插入排序可以聯想到玩撲克牌,當你手上有若干張排好序的牌,又拿起一張新的牌...