1 / 7

Heapsort

Heapsort. CSE 373 Data Structures. Heap Sort. We use a Max-Heap Root node = A[1] Children of A[i] = A[2i], A[2i+1] Keep track of current size N (number of nodes). 7. 7. 5. 6. 2. 4. 5. 6. value. index. 1. 2. 3. 4. 5. 6. 7. 8. 2. 4. N = 5. Using Binary Heaps for Sorting.

posy
Download Presentation

Heapsort

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Heapsort CSE 373 Data Structures

  2. Heap Sort • We use a Max-Heap • Root node = A[1] • Children of A[i] = A[2i], A[2i+1] • Keep track of current size N (number of nodes) 7 7 5 6 2 4 5 6 value index 1 2 3 4 5 6 7 8 2 4 N = 5

  3. Using Binary Heaps for Sorting • Build a max-heap • Do N DeleteMax operations and store each Max element as it comes out of the heap • Data comes out in largest to smallest order • Where can we put the elements as they are removed from the heap? 7 Build Max-heap 5 6 2 4 DeleteMax 6 5 4 2 7

  4. 1 Removal = 1 Addition • Every time we do a DeleteMax, the heap gets smaller by one node, and we have one more node to store • Store the data at the end of the heap array • Not "in the heap" but it is in the heap array 6 6 5 4 2 7 value 5 4 index 1 2 3 4 5 6 7 8 2 7 N = 4

  5. Repeated DeleteMax 5 5 2 4 6 7 2 4 1 2 3 4 5 6 7 8 6 7 N = 3 4 4 2 5 6 7 2 5 1 2 3 4 5 6 7 8 6 7 N = 2

  6. Heap Sort is In-place • After all the DeleteMaxs, the heap is gone but the array is full and is in sorted order 2 2 4 5 6 7 value 4 5 index 1 2 3 4 5 6 7 8 6 7 N = 0

  7. Heapsort: Analysis • Running time • time to build max-heap is O(N) • time for N DeleteMax operations is N O(log N) • total time is O(N log N) • Can also show that running time is (N log N) for some inputs, • so worst case is(N log N) • Average case running time is also O(N log N) • Heapsort is in-place but not stable (why?)

More Related