Often I study some JavaScript
interview questions, suddenly I saw a question about usage of reduce
function for sorting an Array
, I r
A terrible sorting algorithm can be written in a one liner with ES6:
const sorter = (xs, x) => xs.slice(-1)[0] >= x ? [x, ...xs] : [...xs, x];
If the present element is larger or equal the last element of the previously sorted list it is appended to the end, otherwise to the beginning.
[3,4,1].reduce(sorter,[]).reduce(sorter,[])
//returns [1,3,4]
It takes several applications to its return to sort anything but the most simple arrays.
But it will eventually get there. That calls for a recursion!
const arr = [91,4,6,24,8,7,59,3,13,0,11,98,54,23,52,87,4];
const sorter2 =(as) => as.reduce(
(xs, x) => x >= xs.slice(-1)[0] ? [...xs, x]
: xs[0] < x ? sorter2([x, ...xs])
: [x, ...xs],
[],
);
const result = sorter2(arr);
console.log(result.join(', '));
When the present value is larger than the last value of already processed array it is appended. If it is smaller than the first element it is prepended. Only if it is neither before or after the the present value and the accumulated array are sorted again by a recursive call. The method should be equivalent to an insertion sort (please comment!).