Advertisement
4rlen

MERGE SORT

Apr 25th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void mergee(int n, int maintab[], int pocz, int srodek, int kon)
  5. {
  6.     int tabpom[n];
  7.  
  8.     for(int i=pocz; i<=kon; i++)
  9.     {
  10.         tabpom[i] = maintab[i];
  11.     }
  12.  
  13.     int pocz1 = pocz, srodek1 = srodek;
  14.  
  15.     while(pocz <= srodek1 && srodek+1 <= kon)
  16.     {
  17.         if(tabpom[pocz] > tabpom[srodek+1] )
  18.         {
  19.  
  20.             maintab[pocz1] = tabpom[srodek+1];
  21.  
  22.             srodek++; pocz1++;
  23.  
  24.         }
  25.         else
  26.         {
  27.  
  28.             maintab[pocz1] = tabpom[pocz];
  29.  
  30.             pocz++;  pocz1++;
  31.  
  32.         }
  33.  
  34.     }
  35.  
  36.     while (pocz<=srodek1)
  37.  
  38.     {
  39.             maintab[pocz1] = tabpom[pocz]; // w przypadku gdy zbior drugi sie skonczy musimy reszte liczb
  40.                                            // pozostalych ze zbioru 1 wprowadzic do naszej mainowej tablicy
  41.             pocz1++; pocz++;               // jesli wszystko sie zgadza to w ogole nie wejdzie do whila
  42.     }
  43.  
  44. }
  45.  
  46. void mergesort(int n, int tab[], int pocz, int kon)
  47. {
  48.     int srodek;
  49.  
  50.     if(pocz<kon)
  51.     {
  52.         srodek = (pocz+kon)/2;
  53.  
  54.         mergesort(n, tab, pocz, srodek);
  55.  
  56.         mergesort(n, tab, srodek+1, kon);
  57.  
  58.         mergee(n, tab, pocz, srodek, kon);
  59.     }
  60. }
  61. int main()
  62. {
  63.     int n; cin>>n;
  64.  
  65.     int tab[n];
  66.  
  67.     for(int i=0; i<n; i++) {cin >> tab[i];}
  68.  
  69.     int poczatek = 0, koniec = n-1;
  70.  
  71.     mergesort(n, tab, poczatek, koniec);
  72.  
  73.     for(int i=0; i<n; i++)
  74.     {
  75.         cout<<tab[i]<<" ";
  76.     }
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement