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