From 51aa461729f1ea752062fdf79e0344a46aafc55d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20P=C3=B3=C5=82grabia?= Date: Sun, 6 Mar 2022 21:47:05 +0100 Subject: [PATCH] Adding better way of creating leftist heaps using queues. --- 2022/03/algorithms/leftist_heap.js | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/2022/03/algorithms/leftist_heap.js b/2022/03/algorithms/leftist_heap.js index 0b26b7b..5ab9e5a 100644 --- a/2022/03/algorithms/leftist_heap.js +++ b/2022/03/algorithms/leftist_heap.js @@ -55,7 +55,7 @@ function pop_heap(heap) { } function insert_heap(heap, val) { - return merge_heap(heap, {value: val, height: 0}); + return merge_heap(heap, {value: val, height: 1}); } let values = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; @@ -66,8 +66,26 @@ let heap = {root: null}; // heap.root = merge_heap(heap.root, {value: 3, height: 1}); // heap.root = merge_heap(heap.root, {value: -1, height: 1}); -for (let el of values) { - heap.root = merge_heap(heap.root, {value: el, height: 1}); +if (false) { + // naive way of creating leftist heap + for (let el of values) { + heap.root = merge_heap(heap.root, {value: el, height: 1}); + } +} else { + // better way of creating heap using queue + let queue = []; + for (let el of values) { + queue.push({value: el, height: 1}); + } + + while (queue.length > 1) { + let h1 = queue.shift(); + let h2 = queue.shift(); + let h = merge_heap(h1, h2); + queue.push(h); + } + + heap.root = queue.shift(); } while (heap.root) {