-
Notifications
You must be signed in to change notification settings - Fork 1
/
maxheap tree.c
124 lines (110 loc) · 2.02 KB
/
maxheap tree.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
//maxheap tree
#include <stdio.h>
int size = 0;
int swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
return 0;
}
int maxheap(int array[], int size, int i)
{
if (size == 1)
{
printf("Only one element in the tree\n");
}
else
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
swap(&array[i], &array[largest]);
maxheap(array, size, largest);
}
}
return 0;
}
int insert(int array[], int newNum)
{
if (size == 0)
{
array[0] = newNum;
size += 1;
}
else
{
array[size] = newNum;
size += 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
maxheap(array, size, i);
}
}
return 0;
}
int delRoot(int array[], int num)
{
int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}
swap(&array[i], &array[size - 1]);
size -= 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
maxheap(array, size, i);
}
return 0;
}
int printArr(int array[], int size)
{
for (int i = 0; i < size; ++i)
printf("%d\t", array[i]);
return 0;
}
void main()
{
int ele,num;
int array[20];
while(1)
{
printf("\n\nOPERATIONS:\n");
printf("1.Insert element\n2.Delete element\n3.Display tree\n4.Exit program\n");
printf("Enter operation number: ");
scanf("%d",&ele);
switch(ele)
{
case 1:
{
int p;
printf("\nEnter the number to be inserted ");
scanf("%d",&p);
insert(array,p);
}
break;
case 2:
{
int q;
printf("\nEnter the number to be deleted ");
scanf("%d",&q);
delRoot(array,q);
}
break;
case 3:
printArr(array,size);
break;
case 4: exit(0);
default:
printf("Invalid operation number\n");
}
}
}