28. heapSortS12 (1) - 3 HeapSort We can use a heap to sort...

This preview shows page 1 - 3 out of 8 pages.

3. HeapSortWe can use a heap to sort an array.Here we use a max-heap instead of a min-heap.The main idea:•Build a heap from an array.•With a max-heap, we can extract the root to get the largest value, and put it aside (put it as the last element of the array by swapping the root and the last element.)•Then we continue to extract the next root (the second largest value, and put it as the second last element of the array. •After doing this for n-1 times (where n is the number of elements in the initial heap), we will have a sorted (ascending order) array. To have a descending order array, we can use a min-heap.Since sorting an array means to sort any array, first we need to build a heap before we start extracting the roots.
Turning a tree into a max-heap. (Building a max-heap from an array)For each node that has a child node, we call “fixHeap” method.We do this starting the node in the lowest level first, then we do for nodesin the one level above. Then we keep going up to the node in the above leveluntil we call fixHeap on the root.

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture