AdvancedSorting

Max max heap stored in array0 n 1 insert insert a

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: , 15, 14, 14, 9, 4, 3} 22 Heap as a priority queue ! Max Max heap stored in array[0, …, n – 1] ! Insert Insert a new item at location n ! Upward_heapify(array, n) restores heap Function Upward_heapify(array, n): new ← array[n] child ← n parent ← (child-1)/2 while child > 0 and array[parent] < new array[child] ← array[parent] child ← parent parent ← (child-1)/2 23 array[child] ← new Heap priority queue: complexity ! worst case time complexity of insert: time insert: – Traverse all the way to the root (new Traverse element element is maximum) – Since the depth of the almost complete Since BT BT is floor(log2 n), algorithm needs at ), most most floor(log2 n) comparisions and comparisions floor(log floor(log2 n) + 1 copy operations ! Result: (log Result: O(log n) 24 Max Max heap: remove max element ! Remove max element – Example array: { 18, 16, 17, 8, 15, 14, 14, 9, 4, 3} array: 18, – Store max element (e.g. 18) in temporary variable Temporary: 18 16 8 4 17 15 3 14 9 14 25 Max Max heap: remove max element – Replace root by last element in array and remove Replace last last element 16 8 4 17 15 3 14 9 14 26 Max Max heap: remove max element – “sift down” the new value from the end of the “sift array by swapping with the larger child while the larger larger child is greater: 14 16 8 4 17 15 14 9 3 27 Max Max heap: remove max element – If the larger child is equal or smaller, algorithm is If complete complete 17 16 8 4 14 15 14 9 3 New New...
View Full Document

Ask a homework question - tutors are online