Lecture 4: Heaps and heap sortnode
1.堆(Heap)python
堆是一個數組對象,能夠看做是一個類徹底二叉樹(nearly complete binary tree)。api
堆的一些操做:數組
root of tree: first element in the array, corresponding to i = 1 ui
parent(i) =i/2: returns index of node's parent spa
left(i)=2i: returns index of node's left child code
right(i)=2i+1: returns index of node's right child對象
python代碼:排序
def parent(i): return i // 2 def left(i): return 2*i def right(i): return 2*i + 1 #A的第一元素不算在總長度內,至關於A的index從1開始 def heap_size(A): return len(A) - 1
最大堆(Max-Heaps):element
對於每一個節點i都有A[PARENT(i)] ≥ A[i].
MAX HEAPIFY: O(lg n) maintains max-heap property
python代碼:
#O(lg n) maintains max-heap property def Max_Heapify(A,i): l = left(i) r = right(i) if(l <= heap_size(A) and A[l] > A[i]): largest = l else: largest = i if(r <= heap_size(A) and A[r] > A[largest]): largest = r if(largest != i): tmp = A[i] A[i] = A[largest] A[largest] = tmp Max_Heapify(A, largest) return
BUILD MAX HEAP: O(n) produces max-heap from unordered input array
爲何從n/2開始?
Elements A[n/2 ……n] are all leaves of the tree and can’t have children.
python代碼:
def Build_Max_Heap(A): for i in range(heap_size(A) // 2,0,-1): Max_Heapify(A, i) return
2.堆排序(Heap-Sort)
排序過程:
Build max heap from unordered array
Find maximum element (A[1])
Put it in correct position A[n],A[n] goes to A[1] New root could violate max heap property but children remain max heaps.
Discard node n from heap (decrement heapsize)
Heap Sort Algorithm
python代碼:
def Heap_Sort(A): L = [] Build_Max_Heap(A) iSize = heap_size(A) for i in range(iSize,1,-1): tmp = A[i] A[i] = A[1] A[1] = tmp L.insert(0, A.pop()) Max_Heapify(A, 1) return L