-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap.cpp
More file actions
136 lines (120 loc) · 3.07 KB
/
Copy pathheap.cpp
File metadata and controls
136 lines (120 loc) · 3.07 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include <iostream>
using namespace std;
class heap
{
public:
int size = 0;
int *arr; // array pointer , later we will allocate dynamic memory to it :
heap(int n) // constructor for heap class :)
{
size = 0;
arr = new int[n + 1];
arr[0] = -1;
}
void print()
{
for (int i = 1; i <= size; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void insert(int num)
{
size++;
int index = size;
arr[index] = num;
while (index > 1)
{
int parent = index / 2;
if (arr[index] < arr[parent])
break;
else
{
swap(arr[index], arr[parent]);
index = parent;
}
}
}
void deletion()
{
// exception case :
if (size == 1)
{
size--;
return;
}
if (size <= 0)
{
cout << "heap underflow" << endl;
return;
}
// Note - Only root node can be deleted so deletion :)
/*
can be perfomed in two easy peasy steps:
1- replace root node with last node and delete last node
2- place root to it's correct position
*/
// Replacing root with last element :
int temp = arr[1];
arr[1] = arr[size--]; // arr[1] = root , and arr[size]
// find correct position for root node :
int index = 1;
while (index < size)
{
int left_index = 2 * index; // find left and right index
int right_index = 2 * index + 1;
int largest_index = index;
// out of left and right child , choose the biggest one and replace it with root
if (left_index <= size && arr[largest_index] < arr[right_index])
{
largest_index = right_index;
}
if (right_index <= size && arr[largest_index] < arr[left_index])
{
largest_index = left_index;
}
if (largest_index == index)
return;
else
{
swap(arr[index], arr[largest_index]);
index = largest_index;
}
}
cout << "Successfully Deleted : " << temp << endl; // easy laif
}
};
int main()
{
int Heapsize;
cout << "Enter the size for heap : ";
cin >> Heapsize;
heap h(Heapsize);
while (1)
{
int num, choice;
cout << "1-Insertion\n2-Deletion\n3-Print\n4-Exit\n\tYour Choice :" << endl;
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter the element you want to insert : ";
cin >> num;
h.insert(num);
h.print();
break;
case 2:
h.deletion();
break;
case 3:
h.print();
break;
case 4:
exit(1);
default:
cout << "error !" << endl;
break;
}
}
}