heapify in c

Solutions on MaxInterview for heapify in c by the best coders in the world

showing results for - "heapify in c"
Kelley
26 Jan 2021
1// @see https://www.youtube.com/watch?v=H5kAcmGOn4Q
2
3function heapify(list, size, index) {
4    let largest = index;
5    let left = index * 2 + 1;
6    let right = left + 1;
7    if (left < size && list[left] > list[largest]) {
8        largest = left;
9    }
10    if (right < size && list[right] > list[largest]) {
11        largest = right;
12    }
13    if (largest !== index) {
14        [list[index], list[largest]] = [list[largest], list[index]];
15        heapify(list, size, largest);
16    }
17    return list;
18}
19
20function heapsort(list) {
21    const size = list.length;
22    let index = ~~(size / 2 - 1);
23    let last = size - 1;
24    while (index >= 0) {
25        heapify(list, size, --index);
26    }
27    while (last >= 0) {
28        [list[0], list[last]] = [list[last], list[0]];
29        heapify(list, --last, 0);
30    }
31    return list;
32}
33
34heapsort([4, 7, 2, 6, 4, 1, 8, 3]);
similar questions
queries leading to this page
heapify in c