Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- void Merge(int arry[], int low, int middle ,int high)
- {
- int i,j,k;
- int sub1= (middle-low+1);
- int sub2= (high-middle);
- int left[sub1];
- int Right[sub2];
- for( i=0; i<sub1; i++)
- {
- left[i]=arry[low+i];
- }
- for( j=0; j<sub2; j++)
- {
- Right[j]=arry[middle+1+j];
- }
- int cnt1=0,cnt2=0;
- k=low;
- while(cnt1<sub1 && cnt2<sub2)
- {
- if(left[cnt1]<=Right[cnt2])
- {
- arry[k]=left[cnt1];
- cnt1++;
- }
- else
- {
- arry[k]=Right[cnt2];
- cnt2++;
- }
- k++;
- }
- while(cnt1<sub1)
- {
- arry[k]=left[cnt1];
- cnt1++;
- k++;
- }
- while(cnt2<sub2)
- {
- arry[k]=Right[cnt2];
- cnt2++;
- k++;
- }
- }
- void Merge_Sort(int arry[], int low, int high)
- {
- if(low<high)
- {
- int middle = low+(high-low)/2;
- Merge_Sort(arry,low,middle);
- Merge_Sort(arry,middle+1,high);
- Merge(arry,low,middle,high);
- }
- }
- void Dis_play(int arry[],int Size)
- {
- for(int i=0; i<Size; i++)
- {
- cout<<arry[i]<<" ";
- if(i==Size-1)
- {
- cout<<endl;
- }
- }
- }
- int main()
- {
- int n;///size of array
- cout<< "Please enter the size of array:-";
- cin>>n;
- cout<<endl;
- cout<< "Please enter the array:-"<<endl;
- int arry[n];
- for(int i=0; i<n; i++)
- {
- cin>>arry[i];
- }
- cout<<endl;
- cout<< "Before sorting the data is below:-"<<endl;
- Dis_play(arry,n);
- cout<<endl;
- Merge_Sort(arry, 0, n-1);
- cout<< "After sorting the data is:-"<<endl;
- Dis_play(arry,n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement