Advertisement
ruhul0

Heap Sort - Algorithm

Jun 14th, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.03 KB | None | 0 0
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #include<time.h>
  4. #define s 10
  5.  
  6. long a[s];
  7. long heapsize;
  8. void max_heapify(long i){
  9.     long largest;
  10.     long l= 2*i+1;
  11.     long  r=2*i+2 ;
  12.     if (l< heapsize  && a[l] >a[i])
  13.          largest =l;
  14.     else
  15.         largest =i;
  16.     if (r< heapsize  && a[r] >a[largest])
  17.          largest =r;
  18.     if(largest !=i){
  19.         long temp1= a[i];
  20.         a[i]=a[largest];
  21.         a[largest] = temp1;
  22.  
  23.         max_heapify(largest);}
  24. }
  25.  
  26.  
  27. void build_max_heap(){
  28.      heapsize = s ;
  29.     for(long i=(s/2)-1 ;i>=0; i--)
  30.         max_heapify(i);
  31. }
  32. void heap_sort(){
  33.     build_max_heap();
  34.  
  35.     for(long i=s-1; i>0 ;i--)
  36.     {long temp2 = a[i];
  37.     a[i]=a[0];
  38.     a[0]=temp2;
  39.  
  40.     heapsize =heapsize -1;
  41.     max_heapify(0);}
  42. }
  43.  
  44. int main () {
  45.  
  46.     long i=0,j=0,temp;
  47.     clock_t begin,end;
  48.     double time_spent;
  49.     srand(time(NULL));
  50.  
  51.     for(long i= 0; i<s; i++){
  52.          a[i]= rand()%s;}
  53.  
  54.     begin = clock();
  55.     heap_sort();
  56.     end=clock();
  57.     time_spent=(double)(end-begin);
  58.     for(long i=0; i<s; i++){
  59.           printf(" %d  ", a[i]);}
  60.     printf("\nTime Elapsed:%f\n",time_spent);
  61.     return 0;
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement