Advertisement
Quebonamade

Untitled

Dec 9th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include<iostream>
  2. #include<ctime>
  3. #include<cstdlib>
  4. #include<stdio.h>
  5. #include <cmath>
  6. using namespace std;
  7. class BinaryHeap{
  8.     public:
  9.     double* my_array;
  10.     int capacity;
  11.     int heapsize;
  12.  
  13.     BinaryHeap(double* tmparray,int size)
  14.     {
  15.         my_array = tmparray;
  16.         capacity = size;
  17.         heapsize = size;;
  18.     }
  19.     void heapify(int current)
  20.     {
  21.         int largest = current;
  22.         double temp;
  23.         int left = (2 * current) + 1;
  24.         int right = (2 * current) + 2;
  25.         if (left < heapsize && my_array[left] > my_array[largest])
  26.             largest = left;
  27.  
  28.         if (right < heapsize && my_array[right] > my_array[largest])
  29.             largest = right;
  30.  
  31.         if (largest != current) {
  32.             temp = my_array[largest];
  33.             my_array[largest] = my_array[current];
  34.             my_array[current] = temp;
  35.             heapify(largest);
  36.         }
  37.     }
  38.     void buildHeap() {
  39.         for (int i = heapsize - 1; i >= 0; i--)
  40.             heapify(i);
  41.     }
  42.    
  43.     void heapSort() {
  44.         int temp = heapsize;
  45.         for (int i = heapsize - 1; i >= 0; i--) {
  46.             double container = my_array[0];
  47.             my_array[0] = my_array[i];
  48.             my_array[i] = container;
  49.             heapsize = heapsize - 1;
  50.             heapify(0);
  51.         }
  52.         heapsize = temp;
  53.     }
  54.     void printSome() {
  55.         for (int i = 1000000; i < 1000100; i++) {
  56.             cout << my_array[i] << ' ';
  57.         }
  58.     }
  59. };
  60. int main() {
  61.     srand(unsigned(time(NULL)));
  62.     const int size = 10000000;
  63.     double* tab = new double[size];
  64.     for (int i = 0; i < size; i++) {
  65.         tab[i] = ((rand() << 15) + rand()) / (double)pow(2,30);
  66.     }
  67.     clock_t begin, end;
  68.     double time_spent;
  69.    
  70.    
  71.    
  72.     BinaryHeap* myheap = new BinaryHeap(tab, size);
  73.     myheap->buildHeap();
  74.     begin = clock();
  75.     myheap->heapSort();
  76.     //myheap->printSome();
  77.     end = clock();
  78.     time_spent = ((double)end - (double)begin) / CLOCKS_PER_SEC;
  79.     cout <<endl<< "Time spent:" << time_spent;
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement