Advertisement
Jaagdish47

HEAP CODE

Nov 23rd, 2024
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | Source Code | 0 0
  1. Heap CODE
  2. 2A.  Write a program to insert the element into maximum heap.
  3. Form a max heap using following elements:
  4. 15,7,10,2,20,15,80
  5.  
  6. #include<stdio.h>
  7. #include<conio.h>
  8.  
  9. int main() {
  10.     int a[20], i, j, t_no, pos, n;
  11.  
  12.     clrscr(); // Clears the screen
  13.  
  14.     printf("Enter the number of elements in the array: ");
  15.     scanf("%d", &t_no);
  16.  
  17.     for(j = 1; j <= t_no; j++) {
  18.         printf("\nEnter new element: ");
  19.         scanf("%d", &n);
  20.  
  21.         pos = j;
  22.         // Adjust heap for new element
  23.         while((pos / 2 >= 1) && (a[pos / 2] <= n)) {
  24.             a[pos] = a[pos / 2];
  25.             pos = pos / 2;
  26.         }
  27.         a[pos] = n;
  28.  
  29.         printf("\nHeap:\n");
  30.         for(i = 1; i <= j; i++) {
  31.             printf("%d ", a[i]);
  32.         }
  33.     }
  34.  
  35.     getch(); // Wait for a key press
  36.     return 0;
  37. }
  38.  
  39. 2B.  Write a program to insert the element into minimum heap.
  40. Form a min heap using following elements:
  41. 92,65,72,45,55,44,65
  42.  
  43. #include <stdio.h>
  44. #include <conio.h>
  45.  
  46. int main() {
  47.     int a[20], i, j, t_no, pos, n;
  48.  
  49.     clrscr(); // Clears the screen
  50.  
  51.     printf("\n Enter the number of elements in the array: ");
  52.     scanf("%d", &t_no);
  53.  
  54.     for (j = 1; j <= t_no; j++) {
  55.         printf("\n Enter New Element: ");
  56.         scanf("%d", &n);
  57.  
  58.         pos = j;
  59.         // Min-Heap adjustment
  60.         while ((pos / 2 >= 1) && (a[pos / 2] > n)) {
  61.             a[pos] = a[pos / 2];
  62.             pos = pos / 2;
  63.         }
  64.         a[pos] = n;
  65.  
  66.         printf("\n Heap: \n");
  67.         for (i = 1; i <= j; i++) {
  68.             printf("\t %d ", a[i]);
  69.         }
  70.     }
  71.  
  72.     getch(); // Wait for a key press
  73.     return 0;
  74. }
Tags: HEAP CODE
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement