Alternative Shuffle: sắp xếp mảng sao cho lớn nhất, nhỏ nhất, lớn thứ 2, nhỏ thứ 2, ...
Ví dụ
Đầu vào: [11, 7, 9, 3, 5, 1, 13]
Sắp xếp: [1, 3, 5, 7, 9, 11, 13]
Xen kẽ: [13, 1, 11, 3, 9, 5, 7]
Giải pháp
Mã triển khai:
const arr = [11, 7, 9, 3, 5, 1, 13];
const alternateShuffle = arr => {
const sorted = [...arr].sort((a, b) => a - b);
const res = [];
let left = 0, right = sorted.length - 1;
while (left <= right) {
if (left === right) {
res.push(sorted[left]);
} else {
res.push(sorted[right], sorted[left]);
}
left++;
right--;
}
return res;
};
console.log(alternateShuffle(arr));
Kết quả
Đầu ra trong console:
[13, 1, 11, 3, 9, 5, 7]
Sửa code gốc: Code gốc dùng splice trong loop gây phức tạp. Cách two-pointer đơn giản hơn.