Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 375
Sergei Basharov Avatar asked Feb 20 '14 14:02

Sergei Basharov


People also ask

How do you find the position of the largest number in an array?

To find the largest element, the first two elements of array are checked and the largest of these two elements are placed in arr[0] the first and third elements are checked and largest of these two elements is placed in arr[0] . this process continues until the first and last elements are checked.

Which sorting technique will you use to sort an already sorted array with only 2 middle numbers unsorted should be efficient?

We can use Insertion Sort to sort the elements efficiently.

How do you sort part of an array?

Arrays. sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements).


1 Answers

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]
like image 134
Danilo Valente Avatar answered Sep 18 '22 23:09

Danilo Valente