How to sort an array so that the largest value gets in the middle?

arrays, javascript

Solution

Try this:

var arr = [1, 20, 15, 37, 46, 9];
arr.sort(function (a, b) {
    return a - b;
});
var arr1 = arr.slice(0, arr.length / 2);
var arr2 = arr.slice(arr.length / 2, arr.length);
arr2.sort(function (a, b) {
    return b - a;
});
arr = arr1.concat(arr2);
console.log(arr);

This method is resumed to two steps:

[1, 20, 15, 37, 46, 9]    // step 1: sort the entire array
[1, 9, 15, 20, 37, 46]    // step 2: sort the second half of the array
[1, 9, 15, 46, 37, 20]

Problem

Assume I have a simple array: ``` [1, 20, 15, 37, 46, 9] ``` I need to make it look like this: ``` [1, 9, 15, 46, 37, 20] ``` So the idea is to put the largest value or pair of the largest two values in the middle of the array then put decreasing numbers to the right and to the left of it like a pyramid. I have a couple of ideas but they don't seem elegant enough. Please advise.

Original source