-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_functor.cpp
More file actions
75 lines (63 loc) · 1.19 KB
/
heap_functor.cpp
File metadata and controls
75 lines (63 loc) · 1.19 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
#include <iostream>
#include <fstream>
using namespace std;
class MakeHeap
{
private:
int *a, length;
public:
MakeHeap (int *input, int len):a(input),length(len)
{}
int left (int index)
{
return 2*index + 1;
}
int right (int index)
{
return 2 * index + 2;
}
bool operator()(int index)
{
if (index >= length)
return true;
bool isLeftOutOfBound = this->operator()(left(index));
bool isRightOutOfBound = this->operator()(right (index));
if (isLeftOutOfBound)
return false;
else if (isRightOutOfBound)
{
if (a[index] < a[left(index)])
swap (a[index], a[left(index)]);
} else {
int cmpIndex = left(index);
if (a[right(index)] > a[left(index)])
cmpIndex = right(index);
if (a[index] < a[cmpIndex])
swap (a[index], a[cmpIndex]);
}
return false;
}
};
int
main ()
{
int *a = NULL;
int arrayLen = 0;
cin >> arrayLen;
a = new int [arrayLen];
for (int i = 0; i < arrayLen; i++)
{
cin >> a[i];
cout << a[i] << " ";
}
cout << endl;
for (int i = 0; i < arrayLen; i++)
{
MakeHeap mh(a+i, arrayLen-i);
mh(0);
}
for (int i = 0; i < arrayLen; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}