สมมติว่าเรามีอาร์เรย์ของจำนวนเต็ม เราต้องเขียนฟังก์ชันที่ย้ายศูนย์ทั้งหมดไปอยู่ท้ายอาร์เรย์โดยแก้ไขอาร์เรย์ในที่เดิม (in-place)
ฟังก์ชันต้องทำให้ลำดับสัมพัทธ์ของสมาชิกอื่นๆ คงเดิม
ตัวอย่าง
ถ้าอาร์เรย์นำเข้าคือ:
const arr = [0, 11, 0, 22, 67];
อาร์เรย์ควรถูกแก้ไขเป็น:
const output = [11, 22, 67, 0, 0];
ตัวอย่างโค้ด
const arr = [0, 11, 0, 22, 67];
const moveZeroToEnd = (arr = []) => {
const swap = (array, ind1, ind2) => {
const temp = array[ind1];
array[ind1] = array[ind2];
array[ind2] = temp;
};
let j = 0;
for (let i = 0; i < arr.length; ++i) {
if (arr[i] !== 0) {
swap(arr, i, j++);
}
}
while (j < arr.length) {
arr[j++] = 0;
}
};
moveZeroToEnd(arr);
console.log(arr);
ผลลัพธ์
[11, 22, 67, 0, 0]