บทความนี้สาธิตการจัดเรียงอาร์เรย์ที่มีความยาวคู่ และจำนวนค่าคู่/คี่เท่ากัน ให้ค่าคู่อยู่ตำแหน่ง index คู่ (0,2,4...) และค่าคี่อยู่ index คี่ (1,3,5...)
ตัวอย่างโค้ด
const arr = [1, 2, 3, 4, 5, 6];
const arrangeToIndices = (arr = []) => {
let [even, odd] = [0, 1];
while (even < arr.length && odd < arr.length) {
if (arr[even] % 2 === 1 && arr[odd] % 2 === 0) {
[arr[even], arr[odd]] = [arr[odd], arr[even]];
[even, odd] = [even + 2, odd + 2];
} else {
if (0 === arr[even] % 2) {
even += 2;
}
if (1 === arr[odd] % 2) {
odd += 2;
}
}
}
return arr;
};
console.log(arrangeToIndices(arr));
ผลลัพธ์
[2, 1, 4, 3, 6, 5]
คำอธิบาย
ใช้ two pointers: even (เริ่ม 0) และ odd (เริ่ม 1) สลับค่าเมื่อพบค่าคี่อยู่ index คู่ และค่าคู่อยู่ index คี่ พร้อมกัน ขยับ pointer ตามเงื่อนไข
Time complexity: O(n), Space: O(1) in-place