Skip to main content

Heap-Sort(Program)

 Heap-Sort



CODE

๐Ÿ‘‡

  1. #include<stdio.h>
  2. #include<stdlib.h>

  3. void heapsort(int a[], int n);
  4. void heapify(int a[], int  i, int last);
  5. void buildheap(int a[], int n);
  6. void display(int a[], int n);

  7. void heapsort(int a[10], int n)
  8. {
  9. int i,temp;
  10. buildheap(a,n);
  11. printf("\n   Initialize Heap");
  12. display(a,n);
  13. printf("\n");
  14. for(i=n-1; i>=1; i--)
  15. {
  16. temp=a[0];
  17. a[0]=a[i];
  18. a[i]=temp;
  19. printf("\nAfter %d Iteration-->", n-i);
  20. display(a,n);
  21. //printf("\n");
  22. heapify(a, 0, i-1);
  23. }
  24. }
  25. void buildheap(int a[], int n)
  26. {
  27. //convert a[0] ... a[n-1] into heap
  28. int i;
  29. for(i=(n/2)-1; i>=0; i--)
  30. heapify(a,i, n-1);
  31. }

  32. void heapify(int a[], int i, int last)
  33. {
  34. int j, temp, key;
  35. key=a[i];
  36. j=2*i+1;

  37. if((j<last )&&(a[j]<a[j+1]))
  38. j=j+1;
  39. if((j<=last)&&(key < a[j]))
  40. {
  41. temp = a[i];
  42. a[i] = a[j];
  43. a[j] = temp;
  44. heapify(a, j ,last);  
  45. }
  46. }

  47. void display(int a[], int n)
  48. {
  49. int i;
  50. for(i=0; i<n; i++)
  51. printf(" %d ", a[i]);
  52. }

  53. int main()
  54. {
  55. int a[20], n, i;
  56. printf("\t\t>>Heap Sort<<\n");
  57. printf("\n How many element you want to in array..?\t");
  58. scanf("%d",&n);
  59. printf("\n Enter %d Element In Array:\t",n);
  60. for(i=0; i<n; i++)
  61. scanf("%d",&a[i]);
  62. heapsort(a,n);
  63.   printf("\n\n The Sorted Element Are:");
  64. display(a,n);
  65. printf("\n");
  66. return 0;
  67. }


//Output
/*

                >>Heap Sort<<

 How many element you want to in array..?       8

 Enter 8 Element In Array:      26
5
77
1
61
11
80
15

   Initialize Heap 80  61  77  15  5  11  26  1

After 1 Iteration--> 1  61  77  15  5  11  26  80
After 2 Iteration--> 1  61  26  15  5  11  77  80
After 3 Iteration--> 11  15  26  1  5  61  77  80
After 4 Iteration--> 5  15  11  1  26  61  77  80
After 5 Iteration--> 1  5  11  15  26  61  77  80
After 6 Iteration--> 1  5  11  15  26  61  77  80
After 7 Iteration--> 1  5  11  15  26  61  77  80

 The Sorted Element Are: 1  5  11  15  26  61  77  80

*/

Comments