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

Suppose I have a simple array:

[1, 20, 15, 37, 46, 9]

I need to do it like this:

[1, 9, 15, 46, 37, 20]

So, the idea is to place the largest value or a pair of the largest two values ​​in the middle of the array, then place the decreasing numbers to the right and left of it, like a pyramid.

I have a couple of ideas, but they don't seem elegant enough. Please inform.

+3
source share
8 answers

Try the following:

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 resumes in 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]
+2
source

It can be optimized, but it works.

function pyramid (arr) {
    var newArr = [];

    // sort numerically
    arr.sort(function (a, b) {
        return a - b;
    });

    // put the biggest in new array
    newArr.push(arr.pop());

    // keep grabbing the biggest remaining item and alternate
    // between pushing and unshifting onto the new array
    while (arr.length) {
        newArr[arr.length % 2 === 0 ? 'push' : 'unshift'](arr.pop());
    }

    return newArr;
}

pyramid([1, 20, 15, 37, 46, 9] returns [1, 15, 37, 46, 20, 9]

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

javascript, , ( ), / .

[1, 20, 15, 37, 46, 9]

[1, 9, 15, 20, 37, 46]

, .

: python :

tt = sorted([1, 20, 15, 37, 46, 9])
print tt[0:len(tt)/2] + list(reversed(tt[len(tt)/2:len(tt)]))
+1

:

[1, 20, 15, 37, 46, 9].sort(function(a, b) {
    return a - b;
}).map(function(v, i, a) {
    var p = ~~(a.length / 2);
    return i >= p ? a[a.length - i + p - 1] : v;
});

// [1, 9, 15, 46, 37, 20]

, .

+1

- , -

function pyramid(arr){
    var  mid= Math.floor(arr.length/2);
    var a2= arr.sort(function(a,b){return a-b}).splice(mid);
    return arr.concat(a2.reverse());
}

var a1= [1, 20, 15, 37, 46, 9];
pyramid(a1)

/* : () 1,9,15,46,37,20 */

0
var data = [1, 20, 15, 37, 46, 9];
arr = data.sort(function(a, b){return a - b});
console.log(arr);

[1, 9, 15, 20, 37, 46]

0

, , , . "", .

let arr = [361, 324, 289, 256, 225, 196, 169, 144, 121, 100, 81, 64, 49, 36, 25, 16, 9, 4, 1, 0];
arr = arr.slice(arr.length/2).reverse().concat(arr.slice(0,arr.length/2));
// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 361, 324, 289, 256, 225, 196, 169, 144, 121, 100]

arr = arr.filter((v, i)=>i % 2 === 0).reverse().concat(arr.filter((v, i)=>i % 2 === 1));
// [1, 9, 25, 49, 81, 121, 169, 225, 289, 361, 324, 256, 196, 144, 100, 64, 36, 16, 4, 0]
0
source

All Articles