class Pair {
constructor(f, s, t) {
this
.first = f;
this
.second = s;
this
.third = t;
}
compareTo(p) {
return
this
.first - p.first;
}
}
class PriorityQueue {
constructor(comparator = (a, b) => a - b) {
this
.heap = [];
this
.comparator = comparator;
}
size() {
return
this
.heap.length;
}
peek() {
return
this
.heap[0];
}
push(...values) {
values.forEach(value => {
this
.heap.push(value);
this
.bubbleUp(
this
.heap.length - 1);
});
}
pop() {
const poppedValue =
this
.peek();
const bottom =
this
.size() - 1;
if
(bottom > 0) {
this
.swap(0, bottom);
}
this
.heap.pop();
this
.bubbleDown(0);
return
poppedValue;
}
bubbleUp(index) {
while
(index > 0) {
const parentIndex = Math.floor((index + 1) / 2) - 1;
if
(
this
.comparator(
this
.heap[parentIndex],
this
.heap[index]) <= 0) {
break
;
}
this
.swap(parentIndex, index);
index = parentIndex;
}
}
bubbleDown(index) {
while
(
true
) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let smallestChildIndex = index;
if
(
leftChildIndex <
this
.size() &&
this
.comparator(
this
.heap[leftChildIndex],
this
.heap[smallestChildIndex]) <= 0
) {
smallestChildIndex = leftChildIndex;
}
if
(
rightChildIndex <
this
.size() &&
this
.comparator(
this
.heap[rightChildIndex],
this
.heap[smallestChildIndex]) <= 0
) {
smallestChildIndex = rightChildIndex;
}
if
(smallestChildIndex === index) {
break
;
}
this
.swap(smallestChildIndex, index);
index = smallestChildIndex;
}
}
swap(index1, index2) {
[
this
.heap[index1],
this
.heap[index2]] = [
this
.heap[index2],
this
.heap[index1]];
}
}
function
mergeKArrays(arr) {
const output = [];
const pq =
new
PriorityQueue((a, b) => a.compareTo(b));
for
(let i = 0; i < arr.length; i++) {
pq.push(
new
Pair(arr[i][0], i, 0));
}
while
(pq.size() > 0) {
const curr = pq.pop();
const i = curr.second;
const j = curr.third;
output.push(curr.first);
if
(j + 1 < arr[i].length) {
pq.push(
new
Pair(arr[i][j + 1], i, j + 1));
}
}
return
output;
}
const SubarrayType = {
INCREASING: 0,
DECREASING: 1,
};
function
SortKIncDec(A) {
const sorted_subarrays = [];
let subarray_type = SubarrayType.INCREASING;
let start_idx = 0;
for
(let i = 0; i <= A.length; i++) {
if
(i === A.length ||(i > 0 && A[i - 1] < A[i] &&
subarray_type === SubarrayType.DECREASING) ||
(i > 0 &&
A[i - 1] >= A[i] &&
subarray_type === SubarrayType.INCREASING)
) {
if
(subarray_type === SubarrayType.INCREASING) {
sorted_subarrays.push(A.slice(start_idx, i));
}
else
{
const subList = A.slice(start_idx, i).reverse();
sorted_subarrays.push(subList);
}
start_idx = i;
subarray_type =
subarray_type === SubarrayType.INCREASING
? SubarrayType.DECREASING
: SubarrayType.INCREASING;
}
}
return
mergeKArrays(sorted_subarrays);
}
const arr = [57, 131, 493, 294, 221, 339, 418, 458, 442, 190];
const ans = SortKIncDec(arr);
for
(let i = 0; i < ans.length; i++) {
console.log(ans[i] +
" "
);
}