80 likes | 246 Views
Heapsort and d-Heap Neil Tang 02/11/2010. Class Overview. d-Heap Sort using a heap Heapsort. d-Heap. A d-Heap is exactly like a binary heap except that all the nodes have no more than d children. d-Heap. Insertion takes O(log d N). deleteMin takes O(dlog d N)
E N D
Heapsort and d-HeapNeil Tang02/11/2010 CS223 Advanced Data Structures and Algorithms
Class Overview • d-Heap • Sort using a heap • Heapsort CS223 Advanced Data Structures and Algorithms
d-Heap • A d-Heap is exactly like a binary heap except that all the nodes have no more than d children. CS223 Advanced Data Structures and Algorithms
d-Heap • Insertion takes O(logdN). • deleteMin takes O(dlogdN) • Computing the position of a child or the parent takes much more time unless d is a power of 2. CS223 Advanced Data Structures and Algorithms
Sort using a Heap • Perform N deleteMin operations. • Every time, copy the deleted element (min) to a new array. • Copy the elements back to the original array. • Time complexity: NlogN. CS223 Advanced Data Structures and Algorithms
Heapsort CS223 Advanced Data Structures and Algorithms
Heapsort CS223 Advanced Data Structures and Algorithms
Heapsort • Build a (max)heap. • Swap the first and the last element in the current heap. • Update heap size and percolateDown(1) • Go back to the 2nd step until the array is sorted. • Time complexity (worst case): O(N+N*logN) = O(NlogN). • Theorem: The average number of comparisons used to heapsort a random permutation of N distinct items is 2NlogN-O(NloglogN). CS223 Advanced Data Structures and Algorithms