Open In App

Heap Sort for decreasing order using min heap

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Algorithm : 

  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

Implementation:

C++




// C++ program for implementation of Heap Sort
#include <bits/stdc++.h>
using namespace std;
 
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
    int smallest = i; // Initialize smallest as root
    int l = 2 * i + 1; // left = 2*i + 1
    int r = 2 * i + 2; // right = 2*i + 2
 
    // If left child is smaller than root
    if (l < n && arr[l] < arr[smallest])
        smallest = l;
 
    // If right child is smaller than smallest so far
    if (r < n && arr[r] < arr[smallest])
        smallest = r;
 
    // If smallest is not root
    if (smallest != i) {
        swap(arr[i], arr[smallest]);
 
        // Recursively heapify the affected sub-tree
        heapify(arr, n, smallest);
    }
}
 
// main function to do heap sort
void heapSort(int arr[], int n)
{
    // Build heap (rearrange array)
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
 
    // One by one extract an element from heap
    for (int i = n - 1; i >= 0; i--) {
        // Move current root to end
        swap(arr[0], arr[i]);
 
        // call min heapify on the reduced heap
        heapify(arr, i, 0);
    }
}
 
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    cout << "\n";
}
 
// Driver program
int main()
{
    int arr[] = { 4, 6, 3, 2, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    heapSort(arr, n);
 
    cout << "Sorted array is \n";
    printArray(arr, n);
}


Java




// Java program for implementation of Heap Sort
 
import java.io.*;
 
class GFG {
     
    // To heapify a subtree rooted with node i which is
    // an index in arr[]. n is size of heap
    static void heapify(int arr[], int n, int i)
    {
        int smallest = i; // Initialize smallest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2
 
        // If left child is smaller than root
        if (l < n && arr[l] < arr[smallest])
            smallest = l;
 
        // If right child is smaller than smallest so far
        if (r < n && arr[r] < arr[smallest])
            smallest = r;
 
        // If smallest is not root
        if (smallest != i) {
            int temp = arr[i];
            arr[i] = arr[smallest];
            arr[smallest] = temp;
 
            // Recursively heapify the affected sub-tree
            heapify(arr, n, smallest);
        }
    }
 
    // main function to do heap sort
    static void heapSort(int arr[], int n)
    {
        // Build heap (rearrange array)
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);
 
        // One by one extract an element from heap
        for (int i = n - 1; i >= 0; i--) {
             
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
 
            // call min heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }
 
    /* A utility function to print array of size n */
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int arr[] = { 4, 6, 3, 2, 9 };
        int n = arr.length;
 
        heapSort(arr, n);
 
        System.out.println("Sorted array is ");
        printArray(arr, n);
    }
}
 
// This code is contributed by vt_m.


Python3




# Python3 program for implementation
# of Heap Sort
 
# To heapify a subtree rooted with
# node i which is an index in arr[].
# n is size of heap
def heapify(arr, n, i):
    smallest = i # Initialize smallest as root
    l = 2 * i + 1 # left = 2*i + 1
    r = 2 * i + 2 # right = 2*i + 2
 
    # If left child is smaller than root
    if l < n and arr[l] < arr[smallest]:
        smallest = l
 
    # If right child is smaller than
    # smallest so far
    if r < n and arr[r] < arr[smallest]:
        smallest = r
 
    # If smallest is not root
    if smallest != i:
        (arr[i],
         arr[smallest]) = (arr[smallest],
                           arr[i])
 
        # Recursively heapify the affected
        # sub-tree
        heapify(arr, n, smallest)
 
# main function to do heap sort
def heapSort(arr, n):
     
    # Build heap (rearrange array)
    for i in range(int(n / 2) - 1, -1, -1):
        heapify(arr, n, i)
 
    # One by one extract an element
    # from heap
    for i in range(n-1, -1, -1):
         
        # Move current root to end #
        arr[0], arr[i] = arr[i], arr[0]
 
        # call min heapify on the reduced heap
        heapify(arr, i, 0)
 
# A utility function to print
# array of size n
def printArray(arr, n):
     
    for i in range(n):
        print(arr[i], end = " ")
    print()
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 6, 3, 2, 9]
    n = len(arr)
 
    heapSort(arr, n)
 
    print("Sorted array is ")
    printArray(arr, n)
 
# This code is contributed by PranchalK


C#




// C# program for implementation of Heap Sort
using System;
 
class GFG {
     
    // To heapify a subtree rooted with
    // node i which is an index in arr[],
    // n is size of heap
    static void heapify(int[] arr, int n, int i)
    {
        int smallest = i; // Initialize smallest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2
 
        // If left child is smaller than root
        if (l < n && arr[l] < arr[smallest])
            smallest = l;
 
        // If right child is smaller than smallest so far
        if (r < n && arr[r] < arr[smallest])
            smallest = r;
 
        // If smallest is not root
        if (smallest != i) {
            int temp = arr[i];
            arr[i] = arr[smallest];
            arr[smallest] = temp;
 
            // Recursively heapify the affected sub-tree
            heapify(arr, n, smallest);
        }
    }
 
    // main function to do heap sort
    static void heapSort(int[] arr, int n)
    {
        // Build heap (rearrange array)
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);
 
        // One by one extract an element from heap
        for (int i = n - 1; i >= 0; i--) {
             
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
 
            // call min heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }
 
    /* A utility function to print array of size n */
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");
        Console.WriteLine();
    }
 
    // Driver program
    public static void Main()
    {
        int[] arr = { 4, 6, 3, 2, 9 };
        int n = arr.Length;
 
        heapSort(arr, n);
 
        Console.WriteLine("Sorted array is ");
        printArray(arr, n);
    }
}
 
// This code is contributed by vt_m.


Javascript




<script>
 
 
// Javascript program for implementation of Heap Sort
 
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
function heapify(arr, n, i)
{
    var smallest = i; // Initialize smallest as root
    var l = 2 * i + 1; // left = 2*i + 1
    var r = 2 * i + 2; // right = 2*i + 2
 
    // If left child is smaller than root
    if (l < n && arr[l] < arr[smallest])
        smallest = l;
 
    // If right child is smaller than smallest so far
    if (r < n && arr[r] < arr[smallest])
        smallest = r;
 
    // If smallest is not root
    if (smallest != i) {
        [arr[i], arr[smallest]] = [arr[smallest], arr[i]]
 
        // Recursively heapify the affected sub-tree
        heapify(arr, n, smallest);
    }
}
 
// main function to do heap sort
function heapSort(arr, n)
{
    // Build heap (rearrange array)
    for (var i = parseInt(n / 2 - 1); i >= 0; i--)
        heapify(arr, n, i);
 
    // One by one extract an element from heap
    for (var i = n - 1; i >= 0; i--) {
        // Move current root to end
        [arr[0], arr[i]] = [arr[i], arr[0]]
 
        // call min heapify on the reduced heap
        heapify(arr, i, 0);
    }
}
 
/* A utility function to print array of size n */
function printArray(arr, n)
{
    for (var i = 0; i < n; ++i)
        document.write( arr[i] + " ");
    document.write("<br>");
}
 
// Driver program
var arr = [4, 6, 3, 2, 9];
var n = arr.length;
heapSort(arr, n);
document.write( "Sorted array is <br>");
printArray(arr, n);
 
 
 
</script>


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

New Approach

  1. Build a 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.

C++




#include <algorithm>
#include <iostream>
#include <queue>
#include <vector>
 
using namespace std;
 
vector<int> sortArrayInDescendingOrder(vector<int>& arr)
{
    priority_queue<int, vector<int>, greater<int> > minHeap;
 
    for (int num : arr) {
        minHeap.push(num);
    }
 
    vector<int> result;
    while (!minHeap.empty()) {
        int top = minHeap.top();
        minHeap.pop();
        result.insert(result.begin(), top);
    }
 
    return result;
}
 
int main()
{
    vector<int> arr = { 4, 6, 3, 2, 9 };
    vector<int> result = sortArrayInDescendingOrder(arr);
 
    for (int num : result) {
        cout << num << " ";
    }
    cout << endl;
 
    return 0;
}
// This code is contributed by chinmaya121221


Java




import java.util.*;
 
public class Main {
    public static List<Integer>
    sortArrayInDescendingOrder(List<Integer> arr)
    {
        PriorityQueue<Integer> minHeap
            = new PriorityQueue<>();
 
        for (int num : arr) {
            minHeap.add(num);
        }
 
        List<Integer> result = new ArrayList<>();
        while (!minHeap.isEmpty()) {
            int top = minHeap.poll();
            result.add(0, top);
        }
 
        return result;
    }
 
    public static void main(String[] args)
    {
        List<Integer> arr = Arrays.asList(4, 6, 3, 2, 9);
        List<Integer> result
            = sortArrayInDescendingOrder(arr);
 
        for (int num : result) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}


Python3




import heapq
 
 
def sortArrayInDescendingOrder(arr):
    minHeap = []
    for num in arr:
        heapq.heappush(minHeap, num)
 
    result = []
    while minHeap:
        top = heapq.heappop(minHeap)
        result.insert(0, top)
 
    return result
 
 
if __name__ == '__main__':
    arr = [4, 6, 3, 2, 9]
    result = sortArrayInDescendingOrder(arr)
 
    for num in result:
        print(num, end=' ')
    print()


C#




using System;
using System.Collections.Generic;
 
class Program {
    static List<int>
    SortArrayInDescendingOrder(List<int> arr)
    {
        PriorityQueue<int> minHeap
            = new PriorityQueue<int>();
 
        foreach(int num in arr) { minHeap.Push(num); }
 
        List<int> result = new List<int>();
        while (minHeap.Count > 0) {
            int top = minHeap.Top;
            minHeap.Pop();
            result.Insert(0, top);
        }
 
        return result;
    }
 
    static void Main(string[] args)
    {
        List<int> arr = new List<int>{ 4, 6, 3, 2, 9 };
        List<int> result = SortArrayInDescendingOrder(arr);
 
        foreach(int num in result)
        {
            Console.Write(num + " ");
        }
        Console.WriteLine();
    }
}
 
class PriorityQueue<T> where T : IComparable<T> {
    private List<T> _heap;
 
    public int Count
    {
        get { return _heap.Count; }
    }
 
    public T Top
    {
        get { return _heap[0]; }
    }
 
    public PriorityQueue() { _heap = new List<T>(); }
 
    public void Push(T item)
    {
        _heap.Add(item);
        int i = _heap.Count - 1;
        while (i > 0
               && _heap[(i - 1) / 2].CompareTo(_heap[i])
                      > 0) {
            Swap(i, (i - 1) / 2);
            i = (i - 1) / 2;
        }
    }
 
    public void Pop()
    {
        if (_heap.Count == 0)
            throw new InvalidOperationException(
                "PriorityQueue is empty");
 
        int lastIndex = _heap.Count - 1;
        _heap[0] = _heap[lastIndex];
        _heap.RemoveAt(lastIndex);
        lastIndex--;
 
        int i = 0;
        while (true) {
            int leftChild = 2 * i + 1;
            int rightChild = 2 * i + 2;
            if (leftChild > lastIndex)
                break;
 
            int j = leftChild;
            if (rightChild <= lastIndex
                && _heap[rightChild].CompareTo(
                       _heap[leftChild])
                       < 0) {
                j = rightChild;
            }
 
            if (_heap[i].CompareTo(_heap[j]) <= 0)
                break;
 
            Swap(i, j);
            i = j;
        }
    }
 
    private void Swap(int i, int j)
    {
        T temp = _heap[i];
        _heap[i] = _heap[j];
        _heap[j] = temp;
    }
}
// This code is contributed by sarojmcy2e


Javascript




// JavaScript program to sort the array in descending order
 
function sortArrayInDescendingOrder(arr) {
    let minHeap = new MinHeap();
    // Push all elements to the min heap
    for (let num of arr) {
        minHeap.push(num);
    }
 
    let result = [];
    while (!minHeap.isEmpty()) {
        let top = minHeap.top();
        minHeap.pop();
        result.unshift(
            top); // Insert at the beginning of the array
    }
 
    return result;
}
 
class MinHeap {
    constructor() { this.heap = []; }
    push(num) {
        this.heap.push(num);
        this.bubbleUp(this.heap.length - 1);
    }
 
    pop() {
        let top = this.heap[0];
        let last = this.heap.pop();
 
        if (this.heap.length > 0) {
            this.heap[0] = last;
            this.bubbleDown(0);
        }
 
        return top;
    }
 
    top() { return this.heap[0]; }
 
    isEmpty() { return this.heap.length === 0; }
 
    bubbleUp(index) {
        while (index > 0) {
            let parent = Math.floor((index - 1) / 2);
 
            if (this.heap[parent] > this.heap[index]) {
                [ this.heap[parent], this.heap[index] ] =
                    [ this.heap[index], this.heap[parent] ];
                index = parent;
            }
            else {
                break;
            }
        }
    }
 
    bubbleDown(index) {
        while (true) {
            let left = 2 * index + 1;
            let right = 2 * index + 2;
            let smallest = index;
 
            if (left < this.heap.length
                && this.heap[left] < this.heap[smallest]) {
                smallest = left;
            }
 
            if (right < this.heap.length
                && this.heap[right] < this.heap[smallest]) {
                smallest = right;
            }
 
            if (smallest !== index) {
                [ this.heap[index], this.heap[smallest] ] =
                    [
                        this.heap[smallest],
                        this.heap[index]
                    ];
                index = smallest;
            }
            else {
                break;
            }
        }
    }
}
 
// Driver code
let arr = [ 4, 6, 3, 2, 9 ];
 
// Function call
let result = sortArrayInDescendingOrder(arr);
console.log(result.join(" "));


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 .



Previous Article
Next Article

Similar Reads

Convert Min Heap to Max Heap
Given an array representation of min Heap, convert it to max Heap. Examples: Input: arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9} 3 / \ 5 9 / \ / \ 6 8 20 10 / \ /12 18 9 Output: arr[] = {20, 18, 10, 12, 9, 9, 3, 5, 6, 8} 20 / \ 18 10 / \ / \ 12 9 9 3 / \ /5 6 8 Input: arr[] = {3, 4, 8, 11, 13}Output: arr[] = {13, 11, 8, 4, 3} Approach: To solve the p
10 min read
Difference between Min Heap and Max Heap
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Since a heap is a complete binary tree, a heap with N nodes has log N height. It is useful to remove the highest or lowest priority element. It is typically represented as an array. There are two types of Heaps in the data structure. Min-HeapIn a Min-Heap the
3 min read
Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Given the level order traversal of a Complete Binary Tree, determine whether the Binary Tree is a valid Min-Heap Examples: Input : level = [10, 15, 14, 25, 30] Output : True The tree of the given level order traversal is 10 / \ 15 14 / \ 25 30 We see that each parent has a value less than its child, and hence satisfies the min-heap property Input :
6 min read
Sort all even numbers in ascending order and then sort all odd numbers in descending order
Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.Examples: Input: arr[] = {1, 2, 3, 5, 4, 7, 10}Output: arr[] = {7, 5, 3, 1, 2, 4, 10} Input: arr[] = {0, 4, 5, 3, 7, 2, 1}Output: arr[]
15+ min read
Sort a String in decreasing order of values associated after removal of values smaller than X
Given an integer X and a string str consisting of space-separated texts and numbers placed alternately, the task is to sort the string such that texts and numbers appear in decreasing order of numbers associated after removal of all numbers less than X. If two strings have the same values then sort them in the lexicographic order of the string. Exa
8 min read
Sort an array of strings having characters at odd and even indices sorted in decreasing and increasing order respectively
Given an array arr[] consisting of N strings, the task is to first sort the characters at odd and even indices of the string in decreasing and increasing order respectively, for each string of the array and then, sort the modified array. Examples: Input: arr[] = {"ball", "bat", "boy"}Output: albl atb byoExplanation:S[0]="ball" is converted to "albl
7 min read
Minimize moves to sort Array in non decreasing order by breaking elements in two parts
Given an array of arr[] of N integers, the task is to find the minimum number of moves to sort the array in non-decreasing order by splitting any array element into two parts such that the sum of the parts is the same as that element. Examples: Input: arr[] = {3, 4, 2}Output: 2Explanation: The moves are:Split 4 into two parts {2, 2}. Array becomes
5 min read
Operations to Sort an Array in non-decreasing order
Given an array arr[] of integers of size n, the task is to check if we can sort the given array in non-decreasing order(i, e.arr[i] ≤ arr[i+1]) by using two types of operation by performing any numbers of time: You can choose any index from 1 to n-1(1-based indexing) and increase arr[i] and arr[i+1] by any positive numbers.You can choose any index
7 min read
Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers. The task is to sort all even-placed numbers in increasing and odd-placed numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even placed because of its index 0. Examples:
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg