Merge sort in C\C++ (Algorithm, Pseudocode and output)
Merge Sort
Hy guys welcome to Another tutorial of sorting Algorithms. In this tutorial, you will learn about merge sort and it's programming both in C and c++. Until now we have already discussed some other Sorting Techniques like Insertion Sort, Bubble Sort and Selection Sort so if you haven't read them you can do so by clicking so after this tutorial there will be more tutorials on more sorting techniques like Shell Sort, Quick Sort, Bucket Sort, Tree Sort and Heap sort so without further ado let's start.
Merge sort is a very efficient sorting algorithm with a near-optimal number of comparison. The recursive algorithm used for merge sort comes under the category of divide and conquer technique. An array of n elements is split around its centre producing two smaller arrays. After these two arrays are sorted independently, they can be merged to produce the final sorted array. The process of splitting and merging can be carried recursively till there is only one element in the array. An array with 1 element is always sorted
To understand merge sort, we will take an unsorted array as following −
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. Now what We see here is that an array of 8 items is divided into two arrays of size 4.
But this does not change the sequence of appearance of items in the original. Now we will again divide these two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the colour codes given to these lists.
In the next iteration of the combining phase, we compare lists of two data values and merge them into a list of found data values placing all in sorted order.
After the final merging, the list should look like this −
Now we should learn some programming aspects of merge sorting.
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
Merge sort is based on the divide and conquer technique. With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms. It first divides the array into equal halves and then combines them in a sorted manner.
How Merge Sort Works?
To understand merge sort, we will take an unsorted array as following −
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. Now what We see here is that an array of 8 items is divided into two arrays of size 4.
But this does not change the sequence of appearance of items in the original. Now we will again divide these two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the colour codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values, we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values and merge them into a list of found data values placing all in sorted order.
After the final merging, the list should look like this −
Now we should learn some programming aspects of merge sorting.
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
Step 1 − if it is only one element in the list it is already sorted, return. Step 2 − divide the list recursively into two halves until it can no more be divided. Step 3 − merge the smaller lists into new list in sorted order.
Pseudocode
We shall now see the pseudocodes for merge sort functions. As our algorithms point out two main functions − divide & merge.
Merge sort works with recursion and we shall see our implementation in the same way.
procedure mergesort( var a as array )
if ( n == 1 ) return a
var l1 as array = a[0] ... a[n/2]
var l2 as array = a[n/2+1] ... a[n]
l1 = mergesort( l1 )
l2 = mergesort( l2 )
return merge( l1, l2 )
end procedure
procedure merge( var a as array, var b as array )
var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
end if
end while
while ( a has elements )
add a[0] to the end of c
remove a[0] from a
end while
while ( b has elements )
add b[0] to the end of c
remove b[0] from b
end while
return c
end procedure
Program for Merge Sort in C
Output :
Enter no of elements:5 Enter array elements: 12 22 36 5 17 Sorted array is : 5 12 17 22 36
Program for Merge Sort in C++
#include <iostream>
using namespace std;
// A function to merge the two half into a sorted data.
void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already sorted.
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;
// Merge the two parts into temp[].
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k] = a[j];
k++;
j++;
}
}
// Insert all the remaining values from i to mid into temp[].
while (i <= mid)
{
temp[k] = a[i];
k++;
i++;
}
// Insert all the remaining values from j to high into temp[].
while (j <= high)
{
temp[k] = a[j];
k++;
j++;
}
// Assign sorted data stored in temp[] to a[].
for (i = low; i <= high; i++)
{
a[i] = temp[i-low];
}
}
// A function to split array into two parts.
void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
// Merge them to get sorted output.
Merge(a, low, high, mid);
}
}
int main()
{
int n, i;
cout<<"\nEnter the number of data elements to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
MergeSort(arr, 0, n-1);
// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
Output :
Enter the number of data elements to be sorted: 6 Enter element 1: 22 Enter element 2: 36 Enter element 3: 54 Enter element 4: 01 Enter element 5: 12 Enter element 6: 07 Sorted Data ->1->7->12->22->36->54
No comments
If you have any doubts, please let us Know.