6/9/10 ¡ 1 ¡
CS420 ¡lecture ¡five ¡ Priority ¡Queues, ¡Sor:ng ¡
wim ¡ ¡bohm ¡cs ¡ ¡csu ¡
Heaps
- Heap: ¡array ¡representa:on ¡of ¡a ¡
complete ¡binary ¡tree ¡
– every ¡level ¡is ¡completely ¡filled ¡ ¡ ¡ ¡ ¡ ¡except ¡the ¡boHom ¡level: ¡filled ¡from ¡leI ¡ to ¡right ¡
- Can ¡compute ¡the ¡index ¡of ¡parent ¡
and ¡children ¡
– parent(i) ¡= ¡floor(i/2) ¡ ¡ ¡ ¡ ¡ ¡leI(i)= ¡2i ¡ ¡ ¡ ¡ ¡ ¡index(i)=2i+1 ¡
¡ ¡ ¡ ¡ ¡ ¡(for ¡1 ¡based ¡arrays) ¡
- Heap ¡property: ¡A[parent(i)] ¡>= ¡A[i] ¡
16 ¡ 10 ¡ 9 ¡ 3 ¡ 1 ¡ 4 ¡ 2 ¡ 7 ¡ 8 ¡ 14 ¡ 16 ¡14 ¡10 ¡8 ¡ ¡7 ¡9 ¡3 ¡2 ¡4 ¡1 ¡
Heapify ¡
To ¡create ¡a ¡heap ¡at ¡i, ¡assuming ¡leI(i) ¡and ¡right(i) ¡are ¡heaps, ¡ ¡ bubble ¡A[i] ¡down: ¡swap ¡with ¡max ¡ ¡child ¡un:l ¡heap ¡property ¡holds ¡
¡ ¡ ¡ ¡ ¡ ¡heapify(A,i){ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡L=leI(i); ¡R=right(i); ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡if ¡L<=N ¡and ¡A[L] ¡> ¡A[i] ¡ ¡max=L ¡else ¡max ¡= ¡i; ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡if ¡R<=N ¡and ¡A[R]>A[max] ¡ ¡max ¡=R; ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡if ¡max ¡!= ¡i ¡{ ¡ ¡ ¡ ¡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