-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxHeap.cpp
More file actions
100 lines (94 loc) · 1.91 KB
/
Copy pathMaxHeap.cpp
File metadata and controls
100 lines (94 loc) · 1.91 KB
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
#include <iostream>
using namespace std;
void upHeapify(int *heap, int index)
{
int parentIndex = (index - 1) / 2;
int temp;
while (parentIndex >= 0 && heap[parentIndex] < heap[index])
{
temp = heap[parentIndex];
heap[parentIndex] = heap[index];
heap[index] = temp;
index = parentIndex;
parentIndex = (index - 1) / 2;
}
}
void downHeapify(int *heap,int size)
{
int LChild;
int RChild;
int largest;
int temp;
int i = 0;
while (true)
{
LChild = 2 * i + 1;
RChild = 2 * i + 2;
largest = i;
if (LChild < size && heap[LChild] != -1 && heap[LChild] > heap[largest])
{
largest = LChild;
}
if (RChild < size && heap[RChild] != -1 && heap[RChild] > heap[largest])
{
largest = RChild;
}
if (largest == i)
break;
temp = heap[i];
heap[i] = heap[largest];
heap[largest] = temp;
i = largest;
}
}
void insert(int *heap, int size)
{
int value;
for (int i = 0; i < size; i++)
{
cout << "Enter any number: ";
cin >> value;
heap[i] = value;
if (i != 0)
{
upHeapify(heap, i);
}
}
}
void Delete(int *heap,int size)
{
int i = 0;
int temp;
while (i < size)
{
if (heap[i] == -1)
{
break;
}
i++;
}
i--;
temp = heap[i];
heap[i] = heap[0];
heap[0] = temp;
heap[i] = -1;
downHeapify(heap,size);
}
int main(int argc, char const *argv[])
{
int heap[10];
int size = sizeof(heap) / sizeof(int);
//initializing heap
for (size_t i = 0; i < size; i++)
{
heap[i] = -1;
}
insert(heap, size);
//Delete(heap,size);
// for displaying the heap
for (size_t i = 0; i < size; i++)
{
cout << heap[i] << " ";
}
return 0;
}