SHARE
TWEET

Untitled

a guest Mar 24th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. void swap(int arr[], int a, int b) {
  4.     int tmp = arr[a];
  5.     arr[a] = arr[b];
  6.     arr[b] = tmp;
  7. }
  8.  
  9. void max_heap(int arr[], int size) {
  10.     for (int i = 0; i < size; i++) {
  11.         int leftChildIndex = 2 * i + 1,
  12.             righChildtIndex = 2 * i + 2;
  13.  
  14.         if (righChildtIndex >= size || leftChildIndex >= size) {
  15.             break;
  16.         }
  17.  
  18.         if (leftChildIndex < size && arr[i] < arr[leftChildIndex]) {
  19.             swap(arr, i, leftChildIndex);
  20.         }
  21.  
  22.         if (righChildtIndex < size && arr[i] < arr[righChildtIndex]) {
  23.             swap(arr, i, righChildtIndex);
  24.         }
  25.     }
  26. }
  27.  
  28. void print(int arr[], int size) {
  29.     for (int i = 0; i < size; i++) {
  30.         std::cout << arr[i] << " ";
  31.     }
  32.  
  33.     std::cout << std::endl;
  34. }
  35.  
  36. void sort(int arr[], int size) {
  37.     int orginalSize = size;
  38.     while (size - 1 >= 1) {
  39.         max_heap(arr, size);
  40.         print(arr, size);
  41.         swap(arr, 0, size-- - 1);
  42.     }
  43.  
  44.     print(arr, orginalSize);
  45.     std::cout << std::endl;
  46. }
  47.  
  48. int main()
  49. {
  50.     int arr2[] = { 2, 1 };
  51.     sort(arr2, 2);
  52.  
  53.     int arr[] = { 5, 1, 8, 3, 7 };
  54.     sort(arr, 5);
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top