Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. -# include <stdio.h>
  2. int arr[100],n;
  3.  
  4. void display()
  5. { int i;
  6. if(n==0)
  7. {
  8. printf("Heap is empty\n");
  9. return;
  10. }
  11. for(i=0;i<n;i++)
  12. printf("%d ",arr[i]);
  13. printf("\n");
  14. }
  15. void insert(int num,int loc)
  16. {
  17. int par;
  18. while(loc>0)
  19. {
  20. par=(loc-1)/2;
  21. if(num<=arr[par])
  22. {
  23. arr[loc]=num;
  24. return;
  25. }
  26. arr[loc]=arr[par];
  27. loc=par;
  28. }
  29. arr[0]=num; /*assign num to the root node */
  30. }
  31. void del(int num)
  32. {
  33. int left,right,i,temp,par;
  34.  
  35. for(i=0;i<n;i++)
  36. {
  37. if(num==arr[i])
  38. break;
  39. }
  40. if( num!=arr[i] )
  41. {
  42. printf("%d not found in heap\n",num);
  43. return;
  44. }
  45. arr[i]=arr[n-1];
  46. n=n-1;
  47. par=(i-1)/2;
  48. if(arr[i] > arr[par])
  49. {
  50. insert( arr[i],i);
  51. return;
  52. }
  53. left=2*i+1;
  54. right=2*i+2;
  55. while(right < n)
  56. {
  57. if( arr[i]>=arr[left] && arr[i]>=arr[right] )
  58. return;
  59. if( arr[right]<=arr[left] )
  60. {
  61. temp=arr[i];
  62. arr[i]=arr[left];
  63. arr[left]=temp;
  64. i=left;
  65. }
  66. else
  67. {
  68. temp=arr[i];
  69. arr[i]=arr[right];
  70. arr[right]=temp;
  71. i=right;
  72. }
  73. left=2*i+1;
  74. right=2*i+2;
  75. }/*End of while*/
  76. if( left==n-1 && arr[i]<arr[left] )
  77. { temp=arr[i];
  78. arr[i]=arr[left];
  79. arr[left]=temp;
  80. }
  81. }
  82.  
  83. main()
  84. {
  85. int choice,num;
  86. n=0;
  87. while(1)
  88. {
  89. printf("1.Insert\n");
  90. printf("2.Delete\n");
  91. printf("3.Display\n");
  92. printf("4.Quit\n");
  93. printf("Enter your choice : ");
  94. scanf("%d",&choice);
  95. switch(choice)
  96. {
  97. case 1:
  98. printf("Enter the number to be inserted : ");
  99. scanf("%d",&num);
  100. insert(num,n);
  101. n=n+1;
  102. break;
  103. case 2:
  104. printf("Enter the number to be deleted : ");
  105. scanf("%d",&num);
  106. del(num);
  107. break;
  108. case 3:
  109. display();
  110. break;
  111. case 4:
  112. break;
  113. default:
  114. printf("Wrong\n");
  115. }
  116. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement