Advertisement
Siwy_Krzysiek

Sortowanie przez scalanie

Sep 22nd, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3. #include <stdlib.h>
  4.  
  5. using namespace std;
  6.  
  7. void wypisz(int *tab, int wiel);
  8. void losuj(int *tab, int wiel);
  9. void sortuj(int poczatek, int koniec);
  10. void sortuj2(int *tab, int poczatek, int koniec);
  11.  
  12. //const int ilosc=10;
  13. //int dane[ilosc];
  14. //int bufor[ilosc];
  15.  
  16. int main()
  17. {
  18.     const int ilosc2=10;
  19.     int dane2[ilosc2];
  20.  
  21.     losuj(dane2, ilosc2);
  22.     wypisz(dane2, ilosc2);
  23.  
  24.     sortuj2(dane2, 0, ilosc2-1);
  25.     wypisz(dane2, ilosc2);
  26.  
  27. //    losuj(dane, ilosc);
  28. //    wypisz(dane, ilosc);
  29. //
  30. //    sortuj(0, ilosc-1);
  31. //    wypisz(dane, ilosc);
  32.  
  33.     return 0;
  34. }
  35.  
  36.  
  37. void losuj(int *tab, int wiel)
  38. {
  39.     srand(time(NULL));
  40.     for(int i=0; i<wiel; i++) tab[i]=rand()%10;
  41. }
  42.  
  43. void wypisz(int *tab, int wiel)
  44. {
  45.     for(int i=0; i<wiel; i++) cout << tab[i] << " ";
  46.     cout << endl;
  47. }
  48.  
  49. void sortuj(int poczatek, int koniec)
  50. {
  51.  
  52.     int srodek=(poczatek+koniec+1)/2; //i1, i2;
  53.  
  54.     if(srodek-poczatek>1) sortuj(poczatek, srodek-1);
  55.     if(koniec-srodek>0) sortuj(srodek, koniec);
  56.  
  57.     int i1=poczatek, i2=srodek;
  58.  
  59.     for(int i=poczatek; i<=koniec; i++)
  60.         bufor[i] = (i1==srodek || (i2<=koniec && dane[i1]>dane[i2])) ? dane[i2++] : dane[i1++];
  61.     for(int i=poczatek; i<=koniec; i++)
  62.         dane[i]=bufor[i];
  63. }
  64.  
  65.  
  66. void sortuj2(int *tab, int poczatek, int koniec)
  67. {
  68.     static int* bufor = new int[koniec];
  69.  
  70.     int srodek=(poczatek+koniec+1)/2; //i1, i2;
  71.  
  72.     if(srodek-poczatek>1) sortuj2(tab, poczatek, srodek-1);
  73.     if(koniec-srodek>0) sortuj2(tab, srodek, koniec);
  74.  
  75.     int i1=poczatek, i2=srodek;
  76.  
  77.     for(int i=poczatek; i<=koniec; i++)
  78.         bufor[i] = (i1==srodek || (i2<=koniec && tab[i1]>tab[i2])) ? tab[i2++] : tab[i1++];
  79.     for(int i=poczatek; i<=koniec; i++)
  80.         tab[i]=bufor[i];
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement