Advertisement
giovani-rubim

Merge k Sorted Lists

Mar 31st, 2022
985
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const push = (heap, item) => {
  2.     if (item === null) return;
  3.     let index = heap.length;
  4.     const { val } = item;
  5.     while (index !== 0) {
  6.         let parent_index = (index - 1) >> 1;
  7.         const parent = heap[parent_index];
  8.         if (parent.val <= val) break;
  9.         heap[index] = parent;
  10.         index = parent_index;
  11.     }
  12.     heap[index] = item;
  13. };
  14. const updateRoot = (heap) => {
  15.     const [ item ] = heap;
  16.     const { val } = item;
  17.     const { length } = heap;
  18.     let index = 0;
  19.     for (;;) {
  20.         let child_index = (index << 1)|1;
  21.         if (child_index >= length) break;
  22.         let child = heap[child_index];
  23.         let other_index = child_index + 1;
  24.         if (other_index < length && heap[other_index].val < child.val) {
  25.             child = heap[other_index];
  26.             child_index = other_index;
  27.         }
  28.         if (child.val >= val) break;
  29.         heap[index] = child;
  30.         index = child_index;
  31.     }
  32.     heap[index] = item;
  33. };
  34. const pop = (heap) => {
  35.     const node = heap[0];
  36.     const { next } = node;
  37.     if (next !== null) {
  38.         heap[0] = next;
  39.         updateRoot(heap);
  40.     } else if (heap.length === 1) {
  41.         heap.length = 0;
  42.     } else {
  43.         const last = heap[heap.length - 1];
  44.         heap.length--;
  45.         heap[0] = last;
  46.         updateRoot(heap);
  47.     }
  48.     return node;
  49. };
  50. const mergeKLists = (lists) => {
  51.     const heap = [];
  52.     for (let list of lists) push(heap, list);
  53.     if (heap.length === 0) return null;
  54.     const list = pop(heap);
  55.     let foot = list;
  56.     while (heap.length) {
  57.         const node = pop(heap);
  58.         foot.next = node;
  59.         foot = node;
  60.     }
  61.     foot.next = null;
  62.     return list;
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement