Advertisement
CaFc_Versace

Heap Sort Algorithm

Nov 7th, 2013
4,164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<stdio.h>
  2. #Coded by Ashish Khatkar & CaFc Versace
  3. #Greets : Code Plaza
  4.  
  5. void heapify(int a[], int i, int n) {
  6.     int largest;
  7.     int left = (2 * i) + 1;
  8.     int right = (2 * i) + 2;
  9.     if (left < n && a[left] > a[i]) {
  10.         largest = left;
  11.     } else {
  12.         largest = i;
  13.     }
  14.     if (right < n && a[right] > a[largest]) {
  15.         largest = right;
  16.     }
  17.     if (largest != i) {
  18.         int temp = a[i];
  19.         a[i] = a[largest];
  20.         a[largest] = temp;
  21.         heapify(a, largest, n);
  22.     }
  23. }
  24.  
  25. void hsort(int a[], int n) {
  26.     int i;
  27.     for (i = n - 1; i >= 1; i--) {
  28.         int temp = a[i];
  29.         a[i] = a[0];
  30.         a[0] = temp;
  31.         n = n - 1;
  32.         heapify(a, 0, n);
  33.     }
  34. }
  35.  
  36. void main() {
  37.     int i;
  38.     printf("Enter n ");
  39.     int n;
  40.     scanf("%d", & n);
  41.     int a[n];
  42.     printf("Enter elements\n");
  43.     for (i = 0; i < n; i++) {
  44.         scanf("%d", & a[i]);
  45.     }
  46.     printf("Before heapification\n");
  47.     for (i = 0; i < n; i++) {
  48.         printf("%d ", a[i]);
  49.     }
  50.     printf(" ");
  51.     for (i = (n - 1) / 2; i >= 0; i--) {
  52.         heapify(a, i, n);
  53.     }
  54.     printf("\nAfter heapification\n");
  55.     for (i = 0; i < n; i++) {
  56.         printf("%d ", a[i]);
  57.     }
  58.     hsort(a, n);
  59.     printf("\nAfter heap sort\n");
  60.     for (i = 0; i < n; i++) {
  61.         printf("%d ", a[i]);
  62.     }
  63.     printf(" ");
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement