Created
October 9, 2017 22:47
-
-
Save rahuladream/f6ee01259cc9abea0069b7fcb4217b19 to your computer and use it in GitHub Desktop.
Merge Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
void mergesort(int [],int,int); | |
void merge(int[],int,int,int); | |
int main() | |
{ | |
int a[30],p,r,q,n; | |
cout<<"enter the number of element"; | |
cin>>n; | |
cout<<"element :"; | |
for(int i=0; i<n; i++) | |
{ | |
cin>>a[i]; | |
} | |
// Call of initial function | |
mergesort(a,0,n-1); | |
cout<<"\n Array after sorting"; | |
for(int i=0; i<n; i++) | |
{ | |
cout << " -> "<<a[i]; | |
} | |
return 0; | |
} | |
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[i]; | |
k++; | |
j++; | |
} | |
// Assign sorted data stored in temp[] to a[]. | |
for (i = low; i <= high; i++) | |
{ | |
a[i] = temp[i-low]; | |
} | |
} | |
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment