heap

Heap Sort

堆排序是不稳定排序算法,时间复杂度O(nlogn),空间复杂度O(1).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void (int* arr, int n){
for(int pos = n / 2 - 1; pos >= 0; -- pos){
AjustHeap(arr, pos, n);
}
while(n > 0){
swap(arr[0], arr[n - 1]);
AjustHeap(arr, 0, n - 1);
-- n;
}
}

void AjustHeap(int* arr, int node, int n){
int left = node * 2 + 1;
int right = node * 2 + 2;
int max_pos = node;
if (left < n && arr[left] > arr[max_pos]) max_pos = left;
if (right < n && arr[right] > arr[max_pos]) max_pos = right;
if (max_pos != node){
swap(arr[max_pos], arr[node]);
AjustHeap(arr, max_pos, n);
}
}