Advertisement
pedrocasdev

Untitled

Apr 2nd, 2023
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1.   #include <stdio.h>
  2.  
  3.   void swap(int *a, int *b) {
  4.     int tempvar = *a;
  5.     *a = *b;
  6.     *b = tempvar;
  7.   }
  8.  
  9.   void heapify(int arr[], int n, int i) {
  10.     int greatest = i;
  11.     int leftSide = 2 * i + 1;
  12.     int rightSide = 2 * i + 2;
  13.  
  14.     if (leftSide < n && arr[leftSide] > arr[greatest])
  15.       greatest = leftSide;
  16.  
  17.     if (rightSide < n && arr[rightSide] > arr[greatest])
  18.       greatest = rightSide;
  19.     if (greatest != i) {
  20.       swap(&arr[i], &arr[greatest]);
  21.       heapify(arr, n, greatest);
  22.     }
  23.   }
  24.  
  25.   void heapSort(int arr[], int n) {
  26.     for (int i = n / 2 - 1; i >= 0; i--)
  27.       heapify(arr, n, i);
  28.  
  29.  
  30.     for (int i = n - 1; i >= 0; i--) {
  31.       swap(&arr[0], &arr[i]);
  32.  
  33.       heapify(arr, i, 0);
  34.     }
  35.   }
  36.  
  37.   void printArray(int arr[], int n) {
  38.     for (int i = 0; i < n; ++i)
  39.       printf("%d ", arr[i]);
  40.     printf("\n");
  41.   }
  42.  
  43.  
  44.   int main() {
  45.     int arr[] = {1, 12, 9, 5, 6, 10};
  46.     int n = sizeof(arr) / sizeof(arr[0]);
  47.  
  48.     heapSort(arr, n);
  49.  
  50.     printf("Array ordenado com heapsort \n");
  51.     printArray(arr, n);
  52.   }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement