-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap-sort.cc
143 lines (105 loc) · 2.12 KB
/
heap-sort.cc
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
137
138
#include<iostream>
#include<vector>
#include<math.h>
#include<algorithm>
using namespace std;
class Heap
{
public:
Heap (int array[], int size)
{
m_seq.push_back (size); // m_seq[0] stores the total number of nodes
for (int i = 0; i < size; i++)
m_seq.push_back (array[i]);
}
virtual ~Heap()
{
}
void Print ();
void Sort (); // heapsort
private:
int Parent (int i);
int Left (int i);
int Right (int i);
void BuildHeap ();
void MaxHeapify (int i);
private:
vector<int> m_seq;
};
int
Heap::Parent (int i)
{
return floor (i/2);
}
int
Heap::Left (int i)
{
return 2*i;
}
int
Heap::Right (int i)
{
return 2*i + 1;
}
void
Heap::BuildHeap ()
{
// get the last non leaf node, the last leaf node's parant
int start = floor(m_seq.at (0)/2);
for (;start > 0;start--)
MaxHeapify (start);
}
void
Heap::MaxHeapify (int i)
{
int left = Left (i);
int right = Right (i);
int largest = i;
// find the largest value among i and its two child
if ( left <= m_seq.at (0) && (m_seq.at (i) < m_seq.at (left)) )
largest = left;
if ( right <= m_seq.at (0) && (m_seq.at (largest) < m_seq.at (right)) )
largest = right;
if (largest != i)
{
// switch the largest and i
//int tmp = m_seq.at (i);
//m_seq.at (i) = m_seq.at (largest);
//m_seq.at (largest) = tmp;
swap (m_seq.at (i), m_seq.at (largest));
MaxHeapify (largest);
}
}
void
Heap::Print ()
{
for (int i = 1; i < m_seq.size (); i++)
cout << m_seq.at (i) << " ";
cout << endl;
}
void
Heap::Sort ()
{
int last;
BuildHeap ();
while (last > 1)
{
// swap the root(largest value) and the new last
last = m_seq.at (0);
swap (m_seq.at (1), m_seq.at (last));
m_seq.at (0)--;
// re-build the heap from 1 to the new last
MaxHeapify (1);
}
}
int main (int argc, char *argv[])
{
int array[] = {16,4,10,14,7,9,3,2,8,1};
for (int i = 0; i < 10; i++)
cout << array[i] << " ";
cout << endl;
Heap heap (array, sizeof (array)/sizeof (int));
heap.Sort (); // heap sort
heap.Print ();
return 0;
}