有一个数字数组 setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9]
我想对这个集合进行排序,使其具有最小的数字结束和开始以及最大的位于排序集的中心,如下所示 sortedSetNumbers = [0, 2, 3, 9, 7, 3, 1, -2]
。
const setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9];
const result = [0, 2, 3, 9, 7, 3, 1, -2];
function sortNormal(a, b) {
return true; // Please, change this line
}
const sortedSetNumbers = setOfNumbers.sort((a, b) => sortNormal(a, b));
if (sortedSetNumbers === result) {
console.info('Succeeded Normal Distributed');
} else {
console.warn('Failed Normal Distribution');
}
console.log(sortedSetNumbers);
我确信可以使用 Array.prototype.sort()
方法对这些数字进行排序,但是这个排序函数应该是什么样子呢?
编辑:解决方案不必使用 .sort()
来解决。那只是一个想法。
最佳答案
这可能是最幼稚的做法,但排序后不就是简单的左、右、左、右……吗?
const input = [0, 3, 3, 2, 7, 1, -2, 9];
const expected = [0, 2, 3, 9, 7, 3, 1, -2];
const sorted = input.slice().sort();
const output = [];
let side = true;
while (sorted.length) {
output[side ? 'unshift' : 'push'](sorted.pop());
side = !side;
}
console.log(expected.join());
console.log(output.join());
或者简单地说:
const input = [0, 3, 3, 2, 7, 1, -2, 9];
const output = input.slice().sort().reduceRight((acc, val, i) => {
return i % 2 === 0 ? [...acc, val] : [val, ...acc];
}, []);
console.log(output.join());
关于javascript - 按正态分布(高斯分布)对数字数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420458/