heapSort = {
let input = makeInput();
yield* pauser(display(input, { immediate: true }));
function swap(data, i, j) {
var tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
function* heapSort(arr) {
yield* putArrayInHeapOrder(arr);
for (let end = arr.length - 1; end > 0; end--) {
yield display(input, {pos: end, highlight:new Set([end])});
swap(arr, 0, end);
yield* siftElementDownHeap(arr, 0, end);
}
}
function* putArrayInHeapOrder(arr) {
for (let i = Math.floor(arr.length / 2 - 1); i >= 0; i--) {
yield* siftElementDownHeap(arr, i, arr.length);
}
}
function* siftElementDownHeap(heap, i, max) {
while (i < max) {
let i_big = i;
let c1 = 2 * i + 1;
let c2 = c1 + 1;
if (c1 < max && heap[c1] > heap[i_big])
i_big = c1;
if (c2 < max && heap[c2] > heap[i_big])
i_big = c2;
if (i_big == i) return;
yield display(input, {pos: i, highlight:new Set([i])});
swap(heap, i, i_big);
i = i_big;
}
}
yield* heapSort(input);
yield display(input, {done: true});
}