Heapsort and dHeap Neil Tang 02112010 CS 223

  • Slides: 8
Download presentation
Heapsort and d-Heap Neil Tang 02/11/2010 CS 223 Advanced Data Structures and Algorithms 1

Heapsort and d-Heap Neil Tang 02/11/2010 CS 223 Advanced Data Structures and Algorithms 1

Class Overview Ø d-Heap Ø Sort using a heap Ø Heapsort CS 223 Advanced

Class Overview Ø d-Heap Ø Sort using a heap Ø Heapsort CS 223 Advanced Data Structures and Algorithms 2

d-Heap Ø A d-Heap is exactly like a binary heap except that all the

d-Heap Ø A d-Heap is exactly like a binary heap except that all the nodes have no more than d children. CS 223 Advanced Data Structures and Algorithms 3

d-Heap Ø Insertion takes O(logd. N). Ø delete. Min takes O(dlogd. N) Ø Computing

d-Heap Ø Insertion takes O(logd. N). Ø delete. Min takes O(dlogd. N) Ø Computing the position of a child or the parent takes much more time unless d is a power of 2. CS 223 Advanced Data Structures and Algorithms 4

Sort using a Heap Ø Perform N delete. Min operations. Ø Every time, copy

Sort using a Heap Ø Perform N delete. Min operations. Ø Every time, copy the deleted element (min) to a new array. Ø Copy the elements back to the original array. Ø Time complexity: Nlog. N. CS 223 Advanced Data Structures and Algorithms 5

Heapsort CS 223 Advanced Data Structures and Algorithms 6

Heapsort CS 223 Advanced Data Structures and Algorithms 6

Heapsort CS 223 Advanced Data Structures and Algorithms 7

Heapsort CS 223 Advanced Data Structures and Algorithms 7

Heapsort Ø Build a (max)heap. Ø Swap the first and the last element in

Heapsort Ø Build a (max)heap. Ø Swap the first and the last element in the current heap. Ø Update heap size and percolate. Down(1) Ø Go back to the 2 nd step until the array is sorted. Ø Time complexity (worst case): O(N+N*log. N) = O(Nlog. N). Ø Theorem: The average number of comparisons used to heapsort a random permutation of N distinct items is 2 Nlog. N-O(Nloglog. N). CS 223 Advanced Data Structures and Algorithms 8