Advertisement
axita04

heap_sort

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