Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Heap CODE
- 2A. Write a program to insert the element into maximum heap.
- Form a max heap using following elements:
- 15,7,10,2,20,15,80
- #include<stdio.h>
- #include<conio.h>
- int main() {
- int a[20], i, j, t_no, pos, n;
- clrscr(); // Clears the screen
- printf("Enter the number of elements in the array: ");
- scanf("%d", &t_no);
- for(j = 1; j <= t_no; j++) {
- printf("\nEnter new element: ");
- scanf("%d", &n);
- pos = j;
- // Adjust heap for new element
- while((pos / 2 >= 1) && (a[pos / 2] <= n)) {
- a[pos] = a[pos / 2];
- pos = pos / 2;
- }
- a[pos] = n;
- printf("\nHeap:\n");
- for(i = 1; i <= j; i++) {
- printf("%d ", a[i]);
- }
- }
- getch(); // Wait for a key press
- return 0;
- }
- 2B. Write a program to insert the element into minimum heap.
- Form a min heap using following elements:
- 92,65,72,45,55,44,65
- #include <stdio.h>
- #include <conio.h>
- int main() {
- int a[20], i, j, t_no, pos, n;
- clrscr(); // Clears the screen
- printf("\n Enter the number of elements in the array: ");
- scanf("%d", &t_no);
- for (j = 1; j <= t_no; j++) {
- printf("\n Enter New Element: ");
- scanf("%d", &n);
- pos = j;
- // Min-Heap adjustment
- while ((pos / 2 >= 1) && (a[pos / 2] > n)) {
- a[pos] = a[pos / 2];
- pos = pos / 2;
- }
- a[pos] = n;
- printf("\n Heap: \n");
- for (i = 1; i <= j; i++) {
- printf("\t %d ", a[i]);
- }
- }
- getch(); // Wait for a key press
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement