The program sort an array using Merge Sort technique.
Merge Sort
Merge sort is one of the most common sorting techniques and it is based on the divide and conquer paradigm.
This paradigm focuses on the recurring nature of the problem and thus divides it into various branches (or subproblems). This division for sub-problems depends upon the complexity of the problem at hand.
Now, these sub-problems are further broken down recursively till they are solved at the very end and then, are retracted in a backward fashion and all these results are merged together to give a final solution of the problem.
C program to Sort an array using Merge Sort
#include<stdio.h> void merging(int arr[],int a,int b,int a1,int b1) { int temp[50]; int i,j,k; i=a; j=a1; k=0; while(i<=b && j<=b1) { if(arr[i]<arr[j]) temp[k++]=arr[i++]; else temp[k++]=arr[j++]; } while(i<=b) temp[k++]=arr[i++]; while(j<=b1) temp[k++]=arr[j++]; for(i=a,j=0;i<=b1;i++,j++) arr[i]=temp[j]; } void merge_sort(int arr[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; merge_sort(arr,i,mid); merge_sort(arr,mid+1,j); merging(arr,i,mid,mid+1,j); } } int main() { int arr[30],n,i; printf("Enter no of elements:"); scanf("%d",&n); printf("Enter array elements:"); for(i=0;i<n;i++) scanf("%d",&arr[i]); merge_sort(arr,0,n-1); printf("\nSorted array is :"); for(i=0;i<n;i++) printf("%d ",arr[i]); return 0; }
Output:
The time complexity of the merge sort is O (n log n), because of the following reasons:
- The divide phase, finds out the midpoint of each subsequent sub-array, which results in O(1) time for each step.
- In the conquer phase, this is n/2 because this step recursively sorts 2 sub-arrays.
- The merge phase takes O(n) time because it merges all the elements of the array.