class PriorityQueue {
constructor() {
this
.heap = [];
this
.comparator = (a, b) => {
if
(a.rsb > b.rsb) {
return
1;
}
else
if
(a.rsb < b.rsb) {
return
-1;
}
else
if
(a.setbit > b.setbit) {
return
1;
}
else
if
(a.setbit < b.setbit) {
return
-1;
}
else
if
(a.index > b.index) {
return
1;
}
else
{
return
-1;
}
};
}
enqueue(value) {
this
.heap.push(value);
let index =
this
.heap.length - 1;
while
(index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
if
(
this
.comparator(
this
.heap[parentIndex],
this
.heap[index]) <= 0) {
break
;
}
[
this
.heap[parentIndex],
this
.heap[index]] = [
this
.heap[index],
this
.heap[parentIndex],
];
index = parentIndex;
}
}
dequeue() {
if
(
this
.isEmpty()) {
return
undefined;
}
if
(
this
.size() === 1) {
return
this
.heap.shift();
}
const minValue =
this
.heap[0];
this
.heap[0] =
this
.heap.pop();
let index = 0;
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
while
(
(leftChildIndex <
this
.size() &&
this
.comparator(
this
.heap[leftChildIndex],
this
.heap[index]) < 0) ||
(rightChildIndex <
this
.size() &&
this
.comparator(
this
.heap[rightChildIndex],
this
.heap[index]) < 0)
) {
let smallerIndex =
rightChildIndex <
this
.size() &&
this
.comparator(
this
.heap[rightChildIndex],
this
.heap[leftChildIndex]) < 0
? rightChildIndex
: leftChildIndex;
[
this
.heap[index],
this
.heap[smallerIndex]] = [
this
.heap[smallerIndex],
this
.heap[index],
];
index = smallerIndex;
leftChildIndex = 2 * index + 1;
rightChildIndex = 2 * index + 2;
}
return
minValue;
}
isEmpty() {
return
this
.size() === 0;
}
size() {
return
this
.heap.length;
}
peek() {
if
(
this
.isEmpty()) {
return
undefined;
}
return
this
.heap[0];
}
}
class Pair {
constructor(index, rsb, setbit) {
this
.index = index;
this
.rsb = rsb;
this
.setbit = setbit;
}
}
function
rearrange(arr) {
const n = arr.length;
const pq = [];
for
(let i = 0; i < n; i++) {
const k = (arr[i] & -arr[i]);
const setbit = arr[i].toString(2).replace(/0/g,
''
).length;
pq.push(
new
Pair(i, k, setbit));
}
pq.sort((a, b) => {
if
(a.rsb > b.rsb) {
return
-1;
}
else
if
(a.rsb < b.rsb) {
return
1;
}
else
if
(a.setbit < b.setbit) {
return
-1;
}
else
if
(a.setbit > b.setbit) {
return
1;
}
else
if
(a.index < b.index) {
return
-1;
}
else
{
return
1;
}
});
for
(let i = 0; i < n; i++) {
arr[pq[i].index] = i + 1;
}
return
arr;
}
const arr = [4, 5, 6, 7, 8];
const res = rearrange(arr);
console.log(res.join(
' '
));