-
Notifications
You must be signed in to change notification settings - Fork 13
/
heap_sort.ts
55 lines (46 loc) · 1.2 KB
/
heap_sort.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
49
50
51
52
53
54
55
function heapSort(arr: string[]): string[] {
const n = arr.length;
// Build a heap from the given input array
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// One by one extract an element from the heap
for (let i = n - 1; i > 0; i--) {
// move current to root
const temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Perform heapify to make the array an heap again
heapify(arr, i, 0);
}
return arr;
}
/**
* This function performs the Heapify procedure with node i as the root
*
* @param {string[]} arr
* @param {number} n - Size of arr
* @param {number} i
*/
function heapify(arr: string[], n: number, i: number) {
let largest = i; // Initialize the largest as root
const l = 2 * i + 1;
const r = 2 * i + 2;
// If the left child is largest
if (l < n && arr[l] > arr[largest]) {
largest = l;
}
// If the right child is largest
if (r < n && arr[r] > arr[largest]) {
largest = r;
}
// If largest is not root
if (largest !== i) {
const temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
export { heapSort };