-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax_heap_10.c
87 lines (80 loc) · 1.35 KB
/
max_heap_10.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<stdio.h>
#include<stdlib.h>
#define MAX_ELEMENTS 25
int heap[MAX_ELEMENTS];
int n = 0;
void push(int item)
{
int i;
i= ++n;
while((i!=1) && ( item > heap[i/2]))
{
heap[i] = heap[i/2];
i = i/2;
}
heap[i] = item;
}
void pop()
{
int item;
int temp;
int parent, child;
if(n==0)
printf("heap is empty\n");
else
{
item = heap[1];
temp = heap[n--];
parent = 1;
child = 2;
while(child <= n)
{
if(child < n && (heap[child] < heap[child+1]))
child++;
if(temp >= heap[child])
break;
heap[parent] = heap[child];
parent = child;
child *= 2;
}
heap[parent] = temp;
printf("Element removed from heap is %d\n", item);
}
}
void display()
{
int i;
for(i=1; i<=n; i++)
printf("%d\t", heap[i]);
printf("\n");
}
int main()
{
unsigned int choice;
int x;
while(1)
{
printf("1:insert a node to heap \n2:delete a node from heap \n3:display the max heap\n4:exit\n");
scanf("%u", &choice);
switch(choice)
{
case 1: if(n == MAX_ELEMENTS)
{
printf("Heap is full\n");
exit(1);
}
printf("Enter the element to be added to heap\n");
scanf("%d",&x);//x is the element to be pushed
push(x);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
break;
default: printf("Invalid choice... try again\n");
}
}
return 0;
}