堆排序的python實現

2021-09-13 16:43:32 字數 932 閱讀 7105

def max_heapify(heap, heapsize, root):

left = 2*root+1

right = left+1

larger = root

if left < heapsize and heap[larger] < heap[left]:

larger = left

if right < heapsize and heap[larger] < heap[right]:

larger = right

if larger != root:

heap[larger], heap[root] = heap[root], heap[larger]

max_heapify(heap, heapsize, larger)

def build_max_heap(heap):

heap_size = len(heap)

for i in range((heap_size - 1 - 1)//2, -1, -1):

max_heapify(heap, heap_size, i)

def heap_sort(heap):

build_max_heap(heap)

for i in range(len(heap)-1, -1, -1):

heap[0], heap[i] = heap[i], heap[0]

max_heapify(heap, i, 0)

思想:首先建立最大堆,然後每次從最大堆取出最大值放到末尾,重新調整最大堆。

主要在於堆的調整,在max_heapify中實現的,每次從堆頂(已建立最大堆,只不過堆頂元素新插入)開始,向下的過程。

而最大堆的建立build_max_heap的過程是自下而上的,從第乙個非葉子結點開始從下往上建立,子節點對應的父節點為(n-1)//2。

堆排序的Python實現

堆排序主要包含兩個部分 堆建立和堆調整。以下是最大堆 def max heapify heap,heapsize,root 對乙個父節點及其左右孩子節點調整 heap list heapsize 做陣列最大限制,root 根節點位置 left 2 root 1 注意此處下標從0開始,下標為1開始時,...

堆排序的python實現

如圖所示,堆類似於一棵二叉樹,每個節點最多有兩個子結點,根據堆的特點,又分為大頂堆和小頂堆。對於大頂堆,每個結點的值均大於其子結點的值,小頂推則恰恰相反,每個結點的值均小於其子結點的值。而對排序結構雖然類似於二叉樹,不過確是在列表結構上實現排序的,當結點 i 存在子結點時,其左子結點的索引必定為2i...

Python實現堆排序

usr bin env python coding utf 8 堆排序 class heap object 求給定下標i的父節點下標 defparent self,i if i 2 0 return i 2 1 else return i 2 求給定下標i的左孩子下標 defleft self,i ...