Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const push = (heap, item) => {
- if (item === null) return;
- let index = heap.length;
- const { val } = item;
- while (index !== 0) {
- let parent_index = (index - 1) >> 1;
- const parent = heap[parent_index];
- if (parent.val <= val) break;
- heap[index] = parent;
- index = parent_index;
- }
- heap[index] = item;
- };
- const updateRoot = (heap) => {
- const [ item ] = heap;
- const { val } = item;
- const { length } = heap;
- let index = 0;
- for (;;) {
- let child_index = (index << 1)|1;
- if (child_index >= length) break;
- let child = heap[child_index];
- let other_index = child_index + 1;
- if (other_index < length && heap[other_index].val < child.val) {
- child = heap[other_index];
- child_index = other_index;
- }
- if (child.val >= val) break;
- heap[index] = child;
- index = child_index;
- }
- heap[index] = item;
- };
- const pop = (heap) => {
- const node = heap[0];
- const { next } = node;
- if (next !== null) {
- heap[0] = next;
- updateRoot(heap);
- } else if (heap.length === 1) {
- heap.length = 0;
- } else {
- const last = heap[heap.length - 1];
- heap.length--;
- heap[0] = last;
- updateRoot(heap);
- }
- return node;
- };
- const mergeKLists = (lists) => {
- const heap = [];
- for (let list of lists) push(heap, list);
- if (heap.length === 0) return null;
- const list = pop(heap);
- let foot = list;
- while (heap.length) {
- const node = pop(heap);
- foot.next = node;
- foot = node;
- }
- foot.next = null;
- return list;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement