Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees Function to Create a Copy of Binary Search Tree Function to Delete a Leaf Node from a Binary Tree Function to Insert a Node in a Binary Search Tree Given Two Binary Trees, Check if it is Symmetric A Full Binary Tree with n Nodes Applications of Different Linked Lists in Data Structure B+ Tree in Data Structure Construction of B tree in Data Structure Difference between B-tree and Binary Tree Finding Rank in a Binary Search Tree Finding the Maximum Element in a Binary Tree Finding the Minimum and Maximum Value of a Binary Tree Finding the Sum of All Paths in a Binary Tree Time Complexity of Selection Sort in Data Structure How to get Better in Data Structures and Algorithms Binary Tree Leaf Nodes Classification of Data Structure Difference between Static and Dynamic Data Structure Find the Union and Intersection of the Binary Search Tree Find the Vertical Next in a Binary Tree Finding a Deadlock in a Binary Search Tree Finding all Node of k Distance in a Binary Tree Finding Diagonal Sum in a Binary Tree Finding Diagonal Traversal of The Binary Tree Finding In-Order Successor Binary Tree Finding the gcd of Each Sibling of the Binary Tree Greedy Algorithm in Data Structure How to Calculate Space Complexity in Data Structure How to find missing numbers in an Array Kth Ancestor Node of Binary Tree Minimum Depth Binary Tree Mirror Binary Tree in Data Structure Red-Black Tree Insertion Binary Tree to Mirror Image in Data Structure Calculating the Height of a Binary Search Tree in Data Structure Characteristics of Binary Tree in Data Structure Create a Complete Binary Tree from its Linked List Field in Tree Data Structure Find a Specified Element in a binary Search Tree Find Descendant in Tree Data Structure Find Siblings in a Binary Tree Given as an Array Find the Height of a Node in a Binary Tree Find the Second-Largest Element in a Binary Tree Find the Successor Predecessor of a Binary Search Tree Forest of a Tree in Data Structure In Order Traversal of Threaded Binary Tree Introduction to Huffman Coding Limitations of a Binary Search Tree Link State Routing Algorithm in Data Structure Map Reduce Algorithm for Binary Search Tree in Data Structure Non-Binary Tree in Data Structure Quadratic Probing Example in Hashing Scope and Lifetime of Variables in Data Structure Separate Chaining in Data Structure What is Dynamic Data Structure Separate Chaining vs Open Addressing Time and Space Complexity of Linear Data Structures Abstract Data Types in Data Structures Binary Tree to Single Linked List Count the Number of Nodes in the Binary Tree Count Total No. of Ancestors in a Binary Search Tree Elements of Dynamic Programming in Data Structures Find cost of tree with prims algorithm in data structures Find Preorder Successor in a Threaded Binary Tree Find Prime Nodes Sum Count in Non-Binary Tree Find the Right Sibling of a Binary Tree with Parent Pointers Find the Width of the Binary Search Tree Forest trees in Data Structures Free Tree in Data Structures Frequently asked questions in Tree Data Structures Infix, Postfix and Prefix Conversion Time Complexity of Fibonacci Series What is Weighted Graph in Data Structure What is the Advantage of Linear Search?

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.