fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <iomanip>
  4. #include <time.h>
  5. #include <cmath>
  6. using namespace std;
  7.  
  8. void heapty (int tab[], int o, int heapsize)
  9. {
  10.  
  11. int l = 2 * o;
  12. int r = 2 * o;
  13. int largest;
  14.  
  15. if (l <= heapsize && tab[o] < tab[l])
  16. largest = l;
  17. else
  18. largest = o;
  19.  
  20. if (r <= heapsize && tab[largest] < tab[r])
  21. largest = r;
  22.  
  23. if (largest != o)
  24. {
  25. swap(tab[o], tab[largest]);
  26. heapty(tab, largest, heapsize);
  27. }
  28. }
  29.  
  30. void build_heap(int tab[], int heapsize)
  31. {
  32. for (int i = heapsize/2; i >= 0; i--)
  33. heapty(tab, i, heapsize);
  34. }
  35.  
  36. void heap_sort(int tab[], int size)
  37. {
  38. int heapsize = size;
  39. build_heap(tab, heapsize);
  40.  
  41. do {
  42. swap(tab[0], tab[heapsize]);
  43. heapsize--;
  44. heapty(tab, 0, heapsize);
  45. } while (heapsize > 0);
  46. }
  47.  
  48. int main()
  49. {
  50. const int d = 10;
  51. int tab2[d] = { 23, 45, 23, 11, 24, 65, 931, 11, 2, 40 };
  52.  
  53. cout << "PRZED SORTOWANIEM:" << endl << endl;
  54. for (int i = 0; i < d; i++) // wypisanie posortowanej tablicy
  55. cout << "tab[" << i << "] = " << tab2[i] << endl;
  56. cout << endl;
  57.  
  58. heap_sort(tab2, d);
  59.  
  60. cout << "PO SORTOWANIU:" << endl << endl;
  61. for (int i = 0; i < d; i++) // wypisanie posortowanej tablicy
  62. cout << "tab[" << i << "] = " << tab2[i] << endl;
  63.  
  64. system("pause");
  65.  
  66. return 0;
  67. }
Success #stdin #stdout #stderr 0s 3140KB
stdin
Standard input is empty
stdout
PRZED SORTOWANIEM:

tab[0] = 23
tab[1] = 45
tab[2] = 23
tab[3] = 11
tab[4] = 24
tab[5] = 65
tab[6] = 931
tab[7] = 11
tab[8] = 2
tab[9] = 40

PO SORTOWANIU:

tab[0] = 45
tab[1] = 24
tab[2] = 931
tab[3] = 23
tab[4] = 65
tab[5] = 11
tab[6] = 11
tab[7] = 2
tab[8] = 40
tab[9] = 1
stderr
sh: 1: pause: not found