Maintains maintains a heap rooted at position i in

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: array: { 17, 16, 14, 8, 15, 14, 9, 4, 3} 28 Heap as a priority queue ! Maintains Maintains a heap rooted at position i in array[0, …, n], n], assuming that left and right children are heaps Function Downward_heapify(array, i, n): temp_r temp_r ← array[i]; while while ((j = 2*i+1) ≤ n) n) if if (j < n and array[j] < array[j+1]) j ← j+1 if if (temp_r ≥ array[j]) array[j]) break break else else array[i] ← array[j] i←j array[i] array[i] ← temp_r 29 Heap as a priority queue ! Algorithm Algorithm for removing the front element from a max heap stored in array[0, array[0, …, n-1] Array[0] Array[0] ← array[n-1] array[nDownward_heapify(array, 0, n-2) n- 30 Heap Heap priority queue: complexity ! worst case time complexity of remove: time – Traverse all the way to a leaf Traverse – Since the depth of the almost complete BT Since is is floor(log2 n), algorithm needs at most ), floor(log floor(log2 n) comparisions and floor(log2 n) + 1 copy operations copy ! Result: (log Result: O(log n) 31 Sorting using a Heap ! With With a max heap as descending priority queue, the algorithm is just the general selection selection sort: for for i ← 1 to n-1 Upward_heapify(r, i) for for i ← n-1 downto 1 r[i] r[i] ↔ r[0] Downward_heapify(r, 0, i-1) ! Heapsort Heapsort is in-place 32 Sorting using a Heap ! Worst case time complexity: – Inserting one element has complexity: O(log n) Inserting (log – Inserting n element has complexity O(n log n) Inserting log – Likewise with removing n elements: O(n log n) Likewise log – Heapsort worst-case result: O(n log n) worst-case log ! Best Best case (all elements are identical) – Inserting and removing one element: O(1) Inserting – Inserting and removing n identical elements: O(n) Inserting identical – Heapsort best case result: O(n) Heapsort 33 Building heap more efficiently ! Use Down_heapify to build heap for for i ← n/2 - 1 downto 0 n/2 Downward_heapify(r, i, n-1) for for i ← n-1 downto 1 r[i] r[i] ↔ r[0] Downward_heapify(r, 0, i-1) ! O(n) to build heap instead of O(n log n) log 34...
View Full Document

This document was uploaded on 03/06/2014 for the course ECE 368 at Purdue University-West Lafayette.

Ask a homework question - tutors are online