forked from dishanp/Algorithms-For-Software-Developers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap Sort.cpp
29 lines (28 loc) · 820 Bytes
/
Heap Sort.cpp
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
class Solution {
public:
void siftDown(vector<int>& nums, int n, int i){
int biggest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if(l < n && nums[biggest] < nums[l])
biggest = l;
if(r < n && nums[biggest] < nums[r])
biggest = r;
if(biggest != i){
swap(nums[i], nums[biggest]);
siftDown(nums, n, biggest);
}
}
// heapSort(nums);
vector<int> sortArray(vector<int>& nums){
// heapify stage (bottom up approach)
for(int i = nums.size() / 2 - 1; i >= 0; i--)
siftDown(nums, nums.size(), i);
// sorting stage
for(int i = nums.size() - 1; i > 0; i--){
swap(nums[0], nums[i]);
siftDown(nums, i, 0);
}
return nums;
}
};