Merge sort is another sorting technique and has an algorithm that has a reasonably proficient space-time complexity - O(n log n) and is quite trivial to apply. This algorithm is based on splitting a list, into two comparable sized lists, i.e., left and right and then sorting each list and then merging the two sorted lists back together as one.
Merge sort can be done in two types both having similar logic and way of implementation. These are:
- Top down implementation
- Bottom up implementation
Below given figure shows how Merge Sort works:
Algorithm for Merge Sort
- algorithm Merge_Sort(list)
- Pre: list 6= fi
- Post: list has been sorted into values of ascending order
- if list.Count = 1 // when already sorted
- return list
- end if
- m <- list.Count = 2
- left <- list(m)
- right <- list(list.Count - m)
- for i <- 0 to left.Count - 1
- left[i] <- list[i]
- end for
- for i <- 0 to right.Count -1
- right[i] <- list[i]
- end for
- left <- Merg_Sort(left)
- right <- Merge_Sort(right)
- return MergeOrdered(left, right)
- end Merge_Sort
It is to be noted that, Merge sort uses the concept of divide and conquer technique that was invented by John von Neumann in the year 1945.
Example:
#include <iostream>
using namespace std;
void merge(int *,int, int , int );
void mergesort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
return;
}
// Merge sort concepts starts here
void merge(int *a, int low, int high, int mid)
{
int i, j, k, c[50];
i = low;
k = low;
j = mid + 1;
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
c[k] = a[i];
k++;
i++;
}
else
{
c[k] = a[j];
k++;
j++;
}
}
while (i <= mid)
{
c[k] = a[i];
k++;
i++;
}
while (j <= high)
{
c[k] = a[j];
k++;
j++;
}
for (i = low; i < k; i++)
{
a[i] = c[i];
}
}
// from main mergesort function gets called
int main()
{
int a[30], i, b[30];
cout<<"enter the number of elements:";
for (i = 0; i <= 5; i++) { cin>>a[i];
}
mergesort(a, 0, 4);
cout<<"sorted array\n";
for (i = 0; i < 5; i++)
{
cout<<a[i]<<"\t";
}
cout<<"enter the number of elements:";
for (i = 0; i < 5; i++) { cin>>b[i];
}
mergesort(b, 0, 4);
cout<<"sorted array:\n";
for (i = 0; i < 5; i++)
{
cout<<b[i]<<"\t";
}
getch();
}
Output: