Advertisement
_Nishat_tasnim

Recursive marge

Jun 10th, 2022
1,128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void Merge(int arry[], int low, int middle ,int high)
  5. {
  6.     int i,j,k;
  7.     int sub1= (middle-low+1);
  8.     int sub2= (high-middle);
  9.     int left[sub1];
  10.     int Right[sub2];
  11.     for( i=0; i<sub1; i++)
  12.     {
  13.         left[i]=arry[low+i];
  14.     }
  15.     for( j=0; j<sub2; j++)
  16.     {
  17.         Right[j]=arry[middle+1+j];
  18.     }
  19.     int cnt1=0,cnt2=0;
  20.     k=low;
  21.     while(cnt1<sub1 && cnt2<sub2)
  22.     {
  23.         if(left[cnt1]<=Right[cnt2])
  24.         {
  25.             arry[k]=left[cnt1];
  26.             cnt1++;
  27.         }
  28.         else
  29.         {
  30.             arry[k]=Right[cnt2];
  31.             cnt2++;
  32.         }
  33.         k++;
  34.     }
  35.     while(cnt1<sub1)
  36.     {
  37.         arry[k]=left[cnt1];
  38.         cnt1++;
  39.         k++;
  40.     }
  41.     while(cnt2<sub2)
  42.     {
  43.         arry[k]=Right[cnt2];
  44.         cnt2++;
  45.         k++;
  46.     }
  47. }
  48.  
  49. void Merge_Sort(int arry[], int low, int high)
  50. {
  51.     if(low<high)
  52.     {
  53.         int middle = low+(high-low)/2;
  54.         Merge_Sort(arry,low,middle);
  55.         Merge_Sort(arry,middle+1,high);
  56.         Merge(arry,low,middle,high);
  57.     }
  58. }
  59.  
  60. void Dis_play(int arry[],int Size)
  61. {
  62.     for(int i=0; i<Size; i++)
  63.     {
  64.         cout<<arry[i]<<" ";
  65.         if(i==Size-1)
  66.         {
  67.             cout<<endl;
  68.         }
  69.     }
  70. }
  71. int main()
  72. {
  73.     int n;///size of array
  74.     cout<< "Please enter the size of array:-";
  75.     cin>>n;
  76.     cout<<endl;
  77.     cout<< "Please enter the array:-"<<endl;
  78.     int arry[n];
  79.     for(int i=0; i<n; i++)
  80.     {
  81.         cin>>arry[i];
  82.     }
  83.     cout<<endl;
  84.  
  85.     cout<< "Before sorting the data is below:-"<<endl;
  86.     Dis_play(arry,n);
  87.  
  88.     cout<<endl;
  89.    Merge_Sort(arry, 0, n-1);
  90.  
  91.     cout<< "After sorting the data is:-"<<endl;
  92.     Dis_play(arry,n);
  93.     return 0;
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement