class ListNode {
constructor(val = 0, next =
null
) {
this
.val = val;
this
.next = next;
}
}
class MinHeap {
constructor(capacity) {
this
.count = 0;
this
.capacity = capacity;
this
.array = [];
}
}
function
push(head_ref, new_data) {
const new_node =
new
ListNode(new_data);
new_node.next = head_ref;
head_ref = new_node;
return
head_ref;
}
function
swap(a, b) {
const temp = a;
a = b;
b = temp;
return
[a, b];
}
function
min_heapify(min_heap, idx) {
const left = 2 * idx + 1;
const right = 2 * idx + 2;
let smallest = idx;
if
(
left < min_heap.count &&
min_heap.array[left][0].val < min_heap.array[smallest][0].val
) {
smallest = left;
}
if
(
right < min_heap.count &&
min_heap.array[right][0].val < min_heap.array[smallest][0].val
) {
smallest = right;
}
if
(smallest !== idx) {
[min_heap.array[smallest], min_heap.array[idx]] = swap(
min_heap.array[smallest],
min_heap.array[idx]
);
min_heapify(min_heap, smallest);
}
}
function
is_empty(min_heap) {
return
min_heap.count === 0;
}
function
build_min_heap(min_heap) {
const n = min_heap.count - 1;
for
(let i = Math.floor((n - 1) / 2); i >= 0; i--) {
min_heapify(min_heap, i);
}
}
function
populate_min_heap(min_heap, array, n) {
for
(let i = 0; i < n; i++) {
min_heap.array.push([array[i], i]);
min_heap.count += 1;
}
build_min_heap(min_heap);
}
function
extract_min(min_heap) {
if
(is_empty(min_heap)) {
return
null
;
}
const temp = min_heap.array[0][0];
if
(temp.next !==
null
) {
min_heap.array[0] = [temp.next, min_heap.array[0][1]];
}
else
{
min_heap.array[0] = min_heap.array[min_heap.count - 1];
min_heap.count -= 1;
}
min_heapify(min_heap, 0);
return
temp;
}
function
external_sort(array, n) {
const min_heap =
new
MinHeap(n);
populate_min_heap(min_heap, array, n);
let sortedList =
''
;
while
(!is_empty(min_heap)) {
const temp = extract_min(min_heap);
sortedList += `${temp.val} `;
}
console.log(sortedList.trim());
}
const N = 3;
const array =
new
Array(N);
array[0] =
null
;
array[0] = push(array[0], 50);
array[0] = push(array[0], 40);
array[0] = push(array[0], 30);
array[1] =
null
;
array[1] = push(array[1], 45);
array[1] = push(array[1], 35);
array[2] =
null
;
array[2] = push(array[2], 100);
array[2] = push(array[2], 80);
array[2] = push(array[2], 70);
array[2] = push(array[2], 60);
array[2] = push(array[2], 10);
external_sort(array, N);