Skip to content

Commit ea256f2

Browse files
committedSep 1, 2024
Delete from min heap isnt complete yet!
1 parent 671815a commit ea256f2

File tree

3 files changed

+103
-2
lines changed

3 files changed

+103
-2
lines changed
 

‎delete_from_min_heap.cpp

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
void delete_heap(vector<int> &v)
5+
{
6+
v[0] = v[v.size() - 1];
7+
v.pop_back();
8+
int cur = 0;
9+
while (true)
10+
{
11+
int left_idx = cur * 2 + 1;
12+
int right_idx = cur * 2 + 2;
13+
int last_idx = v.size() - 1;
14+
if (left_idx <= last_idx && right_idx <= last_idx)
15+
{
16+
// duitai ache
17+
if (v[left_idx] <= v[right_idx] && v[left_idx] < v[cur])
18+
{
19+
swap(v[left_idx], v[cur]);
20+
cur = left_idx;
21+
}
22+
else if (v[right_idx] <= v[left_idx] && v[right_idx] < v[cur])
23+
{
24+
swap(v[right_idx], v[cur]);
25+
cur = right_idx;
26+
}
27+
else
28+
{
29+
break;
30+
}
31+
}
32+
else if (left_idx <= last_idx)
33+
{
34+
// left ache
35+
if (v[left_idx] < v[cur])
36+
{
37+
swap(v[left_idx], v[cur]);
38+
cur = left_idx;
39+
}
40+
else
41+
{
42+
break;
43+
}
44+
}
45+
else if (right_idx <= last_idx)
46+
{
47+
// right ache
48+
if (v[right_idx] < v[cur])
49+
{
50+
swap(v[right_idx], v[cur]);
51+
cur = right_idx;
52+
}
53+
else
54+
{
55+
break;
56+
}
57+
}
58+
else
59+
{
60+
break;
61+
}
62+
}
63+
}
64+
65+
void print_heap(vector<int> v)
66+
{
67+
for (int val : v)
68+
cout << val << " ";
69+
cout << endl;
70+
}
71+
72+
int main()
73+
{
74+
vector<int> v;
75+
int n;
76+
cin >> n;
77+
78+
while (n--)
79+
{
80+
int x;
81+
cin >> x;
82+
v.push_back(x);
83+
int current_idx = v.size() - 1;
84+
85+
while (current_idx != 0)
86+
{
87+
int parent_idx = (current_idx - 1) / 2;
88+
if (v[parent_idx] < v[current_idx])
89+
swap(v[parent_idx], v[current_idx]);
90+
else
91+
break;
92+
current_idx = parent_idx;
93+
}
94+
}
95+
delete_heap(v);
96+
print_heap(v);
97+
delete_heap(v);
98+
print_heap(v);
99+
100+
return 0;
101+
}

‎delete_from_min_heap.exe

88 KB
Binary file not shown.

‎output.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
25 20 6 15 5 3
2-
20 15 6 3 5
1+
3 20 25 15 5 6
2+
6 20 25 15 5

0 commit comments

Comments
 (0)
Please sign in to comment.