Vikhyath_11

p6

Jul 26th, 2024
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. #include<stdio.h>
  2. int swap(int *a,int *b){
  3. int temp;
  4. temp=*a;
  5. *a=*b;
  6. *b=temp;
  7. }
  8. void heapify(int a[],int i,int n){
  9. int largest=i;
  10. int left=(2*i)+1;
  11. int right=(2*i)+2;
  12. if(left<n && a[left]>a[largest])
  13. {
  14. largest=left;
  15. }
  16. if(right<n && a[right]>a[largest])
  17. {
  18. largest=right;
  19. }
  20. if(largest!=i){
  21. swap(&a[i],&a[largest]);
  22. heapify(a,largest,n);
  23. }
  24. }
  25. void heapsort(int a[],int n){
  26. int i;
  27. for(i=n/2-1;i>=0;i--)
  28. heapify(a,i,n);
  29. for(i=n-1;i>0;i--){
  30. swap(&a[0],&a[i]);
  31. heapify(a,0,i);
  32. }
  33. }
  34. void main(){
  35. int a[1000],n,i;
  36. printf("enter the number:");
  37. scanf("%d",&n);
  38. printf("enter the element:");
  39. for(i=0;i<n;i++){
  40. scanf("%d",&a[i]);
  41. }
  42. heapsort(a,n);
  43. printf("the sorted elements are");
  44. for(i=0;i<n;i++){
  45. printf("%d ",a[i]);
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment