VOOZH about

URL: https://www.geeksforgeeks.org/dsa/heap-sort-for-decreasing-order-using-min-heap/

⇱ Heap Sort for decreasing order using min heap - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Heap Sort for decreasing order using min heap

Last Updated : 22 Feb, 2025

Given an array of elements, sort the array in decreasing order using min heap. 

Examples:

Input : arr[] = {5, 3, 10, 1}
Output : arr[] = {10, 5, 3, 1}

Input : arr[] = {1, 50, 100, 25}
Output : arr[] = {100, 50, 25, 1}

Prerequisite: Heap sort using min heap.

Using Min Heap Implementation - O(n Log n) Time

  1. Build a min heap from the input data. 
  2. At this point, the smallest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree. 
  3. Repeat above steps while size of heap is greater than 1.

Note: Heap Sort using min heap sorts in descending order where as max heap sorts in ascending order


Output
Sorted array is 
9 6 4 3 2 

Time complexity:It takes O(logn) for heapify and O(n) for constructing a heap. Hence, the overall time complexity of heap sort using min heap or max heap is O(nlogn)
Space complexity: O(n) for call stack

Using Priority Queue (or Library Implementation of Heap) - O(n Log n) Time

  1. Create a Priority Queue (or min heap) from the array elements.
  2. Create an empty result array.
  3. While the min heap is not empty:
    a. Remove the minimum element from the heap.
    b. Add the element to the beginning of the result array.
  4. Return the result array.

Output
9 6 4 3 2 

Time Complexity: O(n log n), where n is the number of elements in the array.
Auxiliary Space:  O(1), because it sort the array in place without using extra space that depends on the input size .

Comment
Article Tags: