Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <ctime>
  5.  
  6. using namespace std;
  7.  
  8. void heapSort(int heap[], const int antal);
  9. void nodeSort(int heap[], const int antal, int start);
  10.  
  11. int main()
  12. {
  13.     const int antal = 30000;
  14.     int heap[antal];
  15.     srand(time(NULL));
  16.     heapSort(heap, antal);
  17.     return 0;
  18. }
  19.  
  20. void heapSort(int heap[], const int antal) {
  21.     for (int i = 0; i < antal; i++) {
  22.         heap[i] = (rand() % 150000) + 1;
  23.         cout << heap[i] << "\t";
  24.         if (i % 5 == 0 && i != 0) {
  25.             cout << endl;
  26.         }
  27.     };
  28.  
  29.     int start = antal / 2; // För att få ut sista noden som har ett eller fler barn
  30.     while (start >= 0) {
  31.         nodeSort(heap, start, antal - 1);
  32.         start--;
  33.     }
  34.     int end = antal - 1;
  35.     while (end > 0) {
  36.         int temp = heap[0];
  37.         heap[0] = heap[end];
  38.         heap[end] = temp;
  39.         nodeSort(heap, 0, end - 1);
  40.         end--;
  41.     }
  42.     cout << endl << endl;
  43.     for (int i = 0; i < antal; i++) {
  44.         cout << heap[i] << "\t";
  45.         if (i % 5 == 0 && i != 0) {
  46.             cout << endl;
  47.         }
  48.     };
  49. }
  50.  
  51. void nodeSort(int heap[], int start, int end) {
  52.     int root = start;
  53.     int child, temp;
  54.  
  55.     while (root * 2 < end) {
  56.         child = root * 2;
  57.         if (child < end && heap[child] < heap[child + 1]) {
  58.             child = child + 1;
  59.         }
  60.         if (heap[root] < heap[child]) {
  61.             temp = heap[root];
  62.             heap[root] = heap[child];
  63.             heap[child] = temp;
  64.             root = child;
  65.         }
  66.         else {
  67.             break;
  68.         }
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement