forked from yangshun/lago
-
Notifications
You must be signed in to change notification settings - Fork 0
/
heapSort.ts
48 lines (40 loc) · 1.12 KB
/
heapSort.ts
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
/**
* Reorders elements of array into max binary heap.
* @param {number[]} arr
* @param {number} size
* @param {number} index of the parent node we are comparing
*/
function heapify(arr: Array<number>, size: number, index: number): void {
let largest = index;
const left = 2 * index + 1;
const right = 2 * index + 2;
if (left < size && arr[left] > arr[largest]) {
largest = left;
}
if (right < size && arr[right] > arr[largest]) {
largest = right;
}
if (largest !== index) {
[arr[index], arr[largest]] = [arr[largest], arr[index]];
heapify(arr, size, largest);
}
}
/**
* Sorts an array of elements using heapsort.
* Returns a shallow copy of the sorted array.
* @param {number[]} arr
* @return {number[]} Sorted array
*/
function heapSort(arr: Array<number>): Array<number> {
const result = arr.slice(0);
const size = arr.length;
for (let i = Math.floor(size / 2 - 1); i >= 0; i--) {
heapify(result, size, i);
}
for (let i = size - 1; i >= 0; i--) {
[result[0], result[i]] = [result[i], result[0]];
heapify(result, i, 0);
}
return result;
}
export default heapSort;