Advertisement
satyaki30

corrected heap sort

Nov 24th, 2014
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int heap_size;
  5.  
  6.  
  7. void max_heapify(int *arr, int i)
  8. {
  9.     int left = 2*i +1;
  10.     int right = 2*i +2;
  11.     int largest = i,temp;
  12.  
  13.     if(left < heap_size && arr[left]>arr[i])
  14.     {
  15.         largest = left;
  16.     }
  17.     if(right < heap_size && arr[right] > arr[largest])
  18.     {
  19.         largest = right;
  20.     }
  21.     if(largest!=i)
  22.     {
  23.         temp = arr[largest];
  24.         arr[largest] = arr[i];
  25.         arr[i] = temp;
  26.         max_heapify(arr, largest);
  27.     }
  28. }
  29.  
  30. void buildheap(int*arr)
  31. {
  32.     int j;
  33.     for(j=heap_size/2;j>=0;j--)
  34.     {
  35.         max_heapify(arr,j);
  36.     }
  37. }
  38.  
  39.  
  40. void heap_sort(int *arr, int size)
  41. {
  42.     int j,temp;
  43.     buildheap(arr);
  44.    
  45.    for(j=size - 1;j>=1;j--)
  46.    {
  47.        temp = arr[j];
  48.        arr[j] = arr[0];
  49.        arr[0] = temp;
  50.        heap_size--;
  51.        max_heapify(arr,0);
  52.    }
  53. }
  54.  
  55. int main()
  56. {
  57.     int size,i;
  58.     printf("Enter the size of array : ");
  59.     scanf("%d",&size);
  60.     int *arr;
  61.     arr=(int*)malloc(size*sizeof(int));
  62.     printf("\nEnter the elements \n");
  63.     for(i=0;i<size;i++)
  64.     {
  65.         scanf("%d",&arr[i]);
  66.     }
  67.     printf("\nArray is\n");
  68.     for(i=0;i<size;i++)
  69.         printf("%d\t",arr[i]);
  70.     printf("\n");
  71.     heap_size = size;
  72.     heap_sort(arr,size);
  73.     printf("\n\nSorted array is\n\n");
  74.     for(i=0;i<size;i++)
  75.         printf("%d\t",arr[i]);
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement