×

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap, or heap max. The root element is minimal for min-heap, and maximum for a max heap. Upon forming a heap, we can remove an object from the root and transfer the last element to the root. After this procedure of swapping, we have to heap the whole array again. We can filter the entire array by removing elements from the root.

The complexity of Heap Sort Technique

  • Time Complexity: O(n log n)
  • Space Complexity: O(1)

Input and Output

Input:

A list of unsorted data: 50 4 11 40 32 81 70

Output:

Array before Sorting: 50 4 11 40 32 81 70

Array after Sorting: 4 11 32 40 50 70 81

Algorithm

Input: A data array, and the total number in the array

Output: Max heap using an element in an array

Begin
for k := 1 to size do
node := k
par := floor (node / 2)
while par >= 1 do
if array[par] < array[node] then
swap array[par] with array[node]
node := par
par := floor (node / 2)
done
done
End

What is a Binary Heap?

This Binary Heap is a complete binary tree in which entities are placed in a special order, such that a parental node’s value is greater than its two nodes’ values. The former is called a heap max, while the latter a heap min. The heap can be described through an array or binary tree.

Algorithm for sorting in increasing order:-

  1. Create a maximum heap of the data input.
  2. The greatest element is placed at the root of the heap at this stage. Replace it with the last heap component, then increase the heap size by 1.
  3. Repeat steps above whilst heap size is greater than 1.

How to create a heap?

The heapify procedure can only be implemented to a node if it heaps its children’s nodes. Thus heapification must be carried out in the order from the bottom up.

Using an example let’s understand:

Input data: 6, 20, 2, 7, 1
         6(0)
        /   \
     20(1)   2(2)
    /   \
 7(3)    1(4)

The numbers in bracket represent the indices in the array representation of data.

Applying the heapify procedure to index 1:
         6(0)
        /   \
    20(1)    2(2)
    /   \
7(3)    1(4)
Applying the heapify procedure to index 0:
        20(0)
        /  \
     7(1)  2(2)
    /   \
 6(3)    1(4)
The heapify procedure calls itself recursively to build the heap
 in the top down manner.

Example of heap sort implementation:

// C++ program for implementation of Heap Sort
include
using namespace std;
void heapify(int arr[], int s, int k)
{
    int largest = k; // Initialize largest as root
    int P = 2k + 1; // left = 2k + 1
    int v= 2k + 2; // right = 2k + 2
    if (P < s && arr[P] > arr[largest]) largest = P; // If right child is larger than largest so far
    if (v < s && arr[v] > arr[largest]) largest = v; // If largest is not root
    if (largest != k)
    {
    swap(arr[k], arr[largest]);  // Recursively heapify the affected sub-tree
        heapify(arr, s, largest);
    }
}  // main function to do heap sort
void heapSort(int arr[], int s)
{
    // Build heap (rearrange array)
    for (int k = s / 2 - 1; k >= 0; k--)
    heapify(arr, s, k);  // One by one extract an element from heap
    for (int k=s-1; k>0; k--)
    {
        // Move current root to end
        swap(arr[0], arr[k]);
        // call max heapify on the reduced heap
        heapify(arr, k, 0);
    }
}
/* A utility function to print array of size s */
void printArray(int arr[], int s)
{
    for (int k=0; k<s; ++k)
        cout << arr[k] << " ";
    cout << "\n";
}
// Driver program
int main()
{
    int arr[] = {20, 10, 16, 4, 8, 6, 2, 44};
    int s = sizeof(arr)/sizeof(arr[0]);
    heapSort(arr, s);
    cout << "Sorted array is \n";
    printArray(arr, s);
}
Heap Sort in C++

Related Topics

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

Advantage and disadvantage friend function C++

Friend Function: - A friend function in C++ is a function that can access the private, protected, and public members of a class. In C++, a friend function is a function that...

2 minutes read.

C++ File Handling

File handling is a mechanism that manipulates the data stored in files. File handling store output data from the program to external file and read file data to the program. There...

3 minutes read.

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.