Mic*_*ski 4 javascript sorting normal-distribution gaussian
有一个数字数组,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);Run Code Online (Sandbox Code Playgroud)
我确信可以使用该方法对这些数字进行排序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());Run Code Online (Sandbox Code Playgroud)
或者干脆:
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());Run Code Online (Sandbox Code Playgroud)