-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path130.h
More file actions
31 lines (29 loc) · 731 Bytes
/
130.h
File metadata and controls
31 lines (29 loc) · 731 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
#define LEFTNODE(i) ((i) * 2 + 1)
#define RIGHTNODE(i) ((i) * 2 + 2)
class Solution {
public:
/*
* @param A: Given an integer array
* @return: nothing
*/
void heapify(vector<int> &A) {
// write your code here
if(A.size() <= 1) return;
int p = (A.size() - 1) / 2;
while(p >= 0){
shiftDown(p, A);
p--;
}
}
private:
void shiftDown(int i, vector<int> &A){
while(LEFTNODE(i) < A.size()){
int j = LEFTNODE(i);
if(RIGHTNODE(i) < A.size() && A[j] > A[RIGHTNODE(i)])
j = RIGHTNODE(i);
if(A[i] <= A[j]) break;
swap(A[i], A[j]);
i = j;
}
}
};