class PriorityQueue {
constructor() {
this
.heap = [];
}
offer(value) {
this
.heap.push(value);
this
.bubbleUp();
}
poll() {
if
(
this
.isEmpty()) {
return
null
;
}
const root =
this
.heap[0];
const last =
this
.heap.pop();
if
(
this
.heap.length > 0) {
this
.heap[0] = last;
this
.bubbleDown();
}
return
root;
}
peek() {
return
this
.isEmpty() ?
null
:
this
.heap[0];
}
isEmpty() {
return
this
.heap.length === 0;
}
size() {
return
this
.heap.length;
}
bubbleUp() {
let index =
this
.heap.length - 1;
while
(index > 0) {
const element =
this
.heap[index];
const parentIndex = Math.floor((index - 1) / 2);
const parent =
this
.heap[parentIndex];
if
(parent <= element) {
break
;
}
this
.heap[index] = parent;
this
.heap[parentIndex] = element;
index = parentIndex;
}
}
bubbleDown() {
let index = 0;
while
(
true
) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let smallest = index;
if
(leftChildIndex <
this
.heap.length &&
this
.heap[leftChildIndex] <
this
.heap[smallest]) {
smallest = leftChildIndex;
}
if
(rightChildIndex <
this
.heap.length &&
this
.heap[rightChildIndex] <
this
.heap[smallest]) {
smallest = rightChildIndex;
}
if
(smallest === index) {
break
;
}
const temp =
this
.heap[index];
this
.heap[index] =
this
.heap[smallest];
this
.heap[smallest] = temp;
index = smallest;
}
}
}
function
mergeArrays(a, n, b, m) {
const minHeap =
new
PriorityQueue();
for
(const value of b) {
minHeap.offer(value);
}
for
(let i = 0; i < n; i++) {
if
(a[i] > minHeap.peek()) {
const min = minHeap.poll();
const temp = a[i];
a[i] = min;
minHeap.offer(temp);
}
}
let index = 0;
while
(!minHeap.isEmpty()) {
b[index++] = minHeap.poll();
}
b.sort((x, y) => x - y);
}
function
main() {
const ar1 = [1, 5, 9, 10, 15, 20];
const ar2 = [2, 3, 8, 13];
const m = ar1.length;
const n = ar2.length;
mergeArrays(ar1, m, ar2, n);
console.log(
"After Merging :- \nFirst Array: "
+ JSON.stringify(ar1));
console.log(
"Second Array: "
+ JSON.stringify(ar2));
}
main();