Advertisement
Shailrshah

Heap Sort

Nov 8th, 2013
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int heapsize;
  4. void swap(int *a ,int *b){
  5.     int temp = *a;
  6.     *a = *b;
  7.     *b = temp;
  8. }
  9. void max_heapify(int *a, int i){
  10.     int l = 2*i, r = l+1, largest;
  11.     if(l < heapsize && a[l] > a[i]) largest = l;
  12.     else largest = i;
  13.     if(r < heapsize && a[r] > a[largest]) largest = r;
  14.     if(largest != i){
  15.         swap(&a[i], &a[largest]);
  16.         max_heapify(a, largest);
  17.     }
  18. }
  19. void build_max_heap(int *a){
  20.     for(int i = heapsize/2; i >= 0; i--) max_heapify(a, i);
  21. }
  22. void heapsort(int *a){
  23.     build_max_heap(a);
  24.     for(int i = heapsize-1; i >= 1; i--){
  25.         swap(&a[0], &a[i]);
  26.         heapsize--;
  27.         max_heapify(a, 0);
  28.     }
  29. }
  30. int main(){
  31.     int i, n;
  32.     printf("Number of elements:  ");
  33.     scanf("%d", &n);
  34.     heapsize = n;
  35.     int *a = (int*)malloc(sizeof(int) * n);
  36.     for(i = 0; i < n; i++)  scanf("%d", &a[i]);
  37.     heapsort(a);
  38.     for(i = 0; i < n; i++) printf("\t%d\t", a[i]);
  39.     return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement