forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapify(AC).cpp
More file actions
39 lines (37 loc) · 918 Bytes
/
heapify(AC).cpp
File metadata and controls
39 lines (37 loc) · 918 Bytes
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
#include <algorithm>
using namespace std;
class Solution {
public:
/**
* @param A: Given an integer array
* @return: void
*/
void heapify(vector<int> &A) {
int n = A.size();
if (n < 2) {
return;
}
int i, j, k;
int minVal;
for (i = (n - 1) / 2; i >= 0; --i) {
j = i;
while (j * 2 + 1 <= n - 1) {
k = j;
minVal = A[j];
if (A[j * 2 + 1] < minVal) {
k = j * 2 + 1;
minVal = A[k];
}
if (j * 2 + 2 <= n - 1 && A[j * 2 + 2] < minVal) {
k = j * 2 + 2;
minVal = A[k];
}
if (k == j) {
break;
}
swap(A[j], A[k]);
j = k;
}
}
}
};