×

Heap Sort vs Merge Sort

In this article, we are going to discuss the Heap Sort, Merge sort and the difference between them.

What is Heap Sort?

Heap – A heap is an abstract data type categorised into max-heap and min-heap. For all nodes in a heap, if the root node is greater than its children, it is referred to as the max-heap; if the root node is smaller than its children, it is referred to as the min-heap.

Heap Sort - A heap sort is also based on the comparison and selection method. It considers the given array as a heap, converts it into max-heap or min-heap, and then sorts the array by selecting and eliminating.

The pseudo-code of the functions involved in the heap sort is given below:

Heap Sort (Int A[], n)
{
Heap_size = n;
Build_max_heap(A, Heap_size);
For i = n-1 down to 2
{
Swap(A[1] and A[i];
Heap_size = Heap_size – 1;
Build_max_heap(A, Heap_size);
}
}


Build_max_heap(A, Heap_size)
{
For i = Heap_size/2 down to 1
{
Max_heapify(A, i);
}
}


Max_heapify(A, i)
{
L = Left(i) // Finding the left child
R = Right(i) // Finding the right child
Largest = i
If (L <= Heap_Size(A) and A[L] > A[Largest])
Largest = L
If (R <= Heap_Size(A) and A[R] > A[Largest]
Largest = R
If (Largest != i)
{
Swap (A[Largest] and A[i])
Max_heapify(A, Largest)
}
}

The heap sort involves three functions, the Max_heapify function places the value at the ith index at its correct position in a heap, and the Build_max_heap function converts the given array into a max-heap. The Heap_sort function calls the necessary function until the array gets sorted.

Click on the given link for the implementation of the heap sort https://www.tutorialandexample.com/heap-sort

Let us sort an array using the Heap sort to get its whole idea and steps involved.

Consider an array, A[] = {14, 28, 12, 36, 5, 18, 9} of size = 7. When we call the heap sort function, it further calls the Build_max_heap function and the Build_max_heap function calls the Max_heapify function. After completing the first Build_max_heap function, we get a max heap.

Heap Sort Vs Merge Sort

Now, we have a max-heap of height = 3.

Pass 1 – Swap (36 and 9). After swapping, the largest value reaches the last index at its correct position. Now, call the max-heapify at index = 0 to convert it into a max-heap with the number of elements = 6.

Heap Sort Vs Merge Sort

Pass 2 – Swap (28 and 12). After swapping, 28 reaches its correct position at index = 5. We again call the max-heapify at index = 0 to convert it into a max-heap with the number of elements = 5.

Heap Sort Vs Merge Sort

Pass 3 - Swap (18 and 5). After swapping, 18 reaches its correct position at index = 4. We again call the max-heapify at index = 0 to convert the remaining array into a max-heap with the number of elements = 4.

Heap Sort Vs Merge Sort

We continue the same procedure for the other passes.

Pass 4 – Swap (14 and 5). After swapping, 14 reaches its correct position at index = 3.

Heap Sort Vs Merge Sort

Pass 5 - Swap (12 and 5). After swapping, 12 reaches its correct position at index = 2.

Heap Sort Vs Merge Sort

Pass 6 - Swap (9 and 5). After swapping, 9 and 5 reach their correct positions at index = 1 and 0, respectively.

Heap Sort Vs Merge Sort

After complete execution of the heap sort function, we get a sorted array as the output.

Let’s move to the next sorting technique Merge Sort

What is Merge Sort?

Merge Sort – The merge sort is a divide and conquer technique that divides a bigger problem into two sub-problems, and each sub-problem is further addressed separately. The out of the program is formed by combining all the results of each sub-problems.

The Pseudo-code of the Merger sort function is given below:

Merge_sort (A, L, U)
{
If(L<U)
{
M = (L + U)/2
Merge_sort (A, L, M);
Merger_sort (A, M + 1, L);
Merge (A, L, M, U);
}
} // L -> Lower Bound, M -> Middle Index, and U -> Upper bound


Merge (A, L, M, U)
{
N1 = M – L + 1;
N2 = U – M;
Create New Array A1[0 to N1] and A2[0 to N2]
For i = 0 to N1
A1[i] = A[ L + i]
For j = 0 to N2
A2[j] = A[M + j]
A1[N1] = Infinity
A2[N2] = Infinity
i = 0;
j = 0;


For k = L to U
If(A1[i] <= A2[j])
{
A[k] = A1[i];
i = i + 1;
}
Else
{
A[k] = A2[j];
j = j + 1;
}
}

The Merge sort function divides the problems into two subproblems of size L to M and M+1 to U, and the Merge function merges the two subproblems into one. In the Merge function, we store infinity at the last index of the newly created arrays A1 and A2. The idea is if somehow one array becomes empty, the elements of the other array are compared with the infinity and placed in array A.

Dividing and Merging Method

An array passed to the merge sort function is divided from the index 0 to n/2 and (n/2 + 1) to n-1, where n is the number of elements in the array. A1[0 to n/2] and A2[n/2 + 1 to n-1], these two problems are further divided until the size of the sub-problem becomes equal to 1. After that, the Merge function merges the subproblems and places all the elements in the right order. The same is shown in the given figure.

Heap Sort Vs Merge Sort

Let us take understand the above idea through an example:

Consider an unsorted array a[] = {36, 15, 12, 28, 16, 9, 22} of size equal to 7. The steps included in sorting the given array are listed below:

Step 1– In the first step, the array of size = 7 is divided into two sub-problems of sizes 4 and 3. We have two Merge sort function calls Merge_sort(A, 0, 3) and Merge_sort(A, 4, 6)and one Merge function call Merge(A, 0, 3, 6). The first Merge_Sort function is solved in the next step, and the rest of the statements are stored in the stack.

Step 2 – Merge_sort(A, 0, 3) is called in the second step. Now, we again have two merge sort function calls Merge_sort(A, 0, 1) and Merge_sort(A, 2, 3) and one Merge function call Merge(A, 0, 1, 3). Merge_sort(A, 0, 1) is called first, and the rest of the function calls are stored in the stack.

Step 3 – The Merge_sort(A, 0, 1) is called. We have Merge_sort(A, 0, 0), Merge(A, 1, 1) and Merge(A, 0, 0, 1). For the first time, we have two merge sort function calls where L and U are equal. Now, the subproblems size is 1; hence Merge function is called for the First time.

Step 4 – The Merge(A, 0, 0, 1) is called. It merges the elements present at the index 0 and 1 in the right order. 15 is stored at index 0, and 36 is stored at index 1.

Step 5 – Like above, other function calls are made and executed. Here, Merge_sort(A, 2, 3) is called. It is further divided and Merged by the program. For this function call, 12 and 28 are placed at the index = 2 and 3, respectively.

Step 6 – The Merge(A, 0, 1, 3) is called and executed by the program. The half of the array gets sorted in this step. The elements of Array A from the index 0 to 3 are placed in a sorted manner. A[0 -> 3] = {12, 15, 28, 36}.

Step 7 – Till here, we have completed half of the program. Merge_sort(A, 4, 6) is called and executed in this step. We further call Merge_sort(A, 4, 5), Merge_sort(A, 6, 6), and Merge(A, 4, 5, 6).

Step 8 – The Merge_sort(A, 4, 5) is called. We divide it into two subproblems of sizes 1 and merge them afterwards. Now, we call the Merge(A, 4, 5, 6). After executing this merge call, we get A[4 -> 6} = {9, 16, 22}.

Step 9 – In the last step, We merge A[0 -> 3] = {12, 15, 28, 36} and A[4 -> 6} = {9, 16, 22}. After merging them, we get A[0 -> 6] = {9, 12, 15, 16, 22, 28, 36}.

Difference between Heap Sort and Merge Sort:

Heap Sort Vs Merge Sort

The main difference between Heap Sort and Merge Sort are listed below in the table:

Heap SortMerge Sort
The idea is to convert the given array into a heap and then sort the array by placing the root element at the last index and repeating the same process for the remaining n-1 elements.The idea is to divide a problem into two subproblems and merge the element of these two subproblems into one. Each subproblem is divided into two subproblems until their size becomes equal to 1.
Time Complexities:
Worst Case: T(n) = O(nlogn)
Average Case: T(n) = O(nlogn)
Best Case: T(n) = O(nlogn)
Time Complexities:
Worst Case: T(n) = O(nlogn)
Average Case: T(n) = O(nlogn)
Best Case: T(n) = O(nlogn)
The space complexity of the heap sort is O(1). It does not require any extra space.The space complexity of the Merge sort is O(n). It requires extra space.
The heap sort is slower than the Merge Sort.The Merge Sort runs slow for arrays of small sizes and faster for large ones.
It is an unstable sorting algorithm. The order of the identical elements does not remain preserved.It is a stable sorting algorithm. The order of identical elements remains preserved.
It uses the idea of Binary heaps.It uses dividing, comparing and merging ideas.
The heap sort has the time complexity as a ‘divide and conquer’ method, but it’s similar to the selection sort.It is a ‘divide and conquer’ sorting method.

Related Topics

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Singly Linked list

Singly Linked list A singly linked list is a kind of linked list which is unidirectional. If we talk about singly linked list, then we can say it can be traversed...

3 minutes read.

Height of a binary tree

The height of a binary tree is generally defined as the height or length of the root _nod in the entire binary tree. In simple words, the height of a...

4 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Delete a Node without head pointer from the linked list

Delete a Node without head pointer from the linked list This article will explain how to delete a node without a head pointer from the linked list. We have given a...

2 minutes read.

What is Skewed Binary Tree

To understand the skewed binary tree, we must first understand the concept of a binary tree. A binary is generally the one in which every single node has two further...

3 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

3 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

7 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.