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.
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.
We can use Insertion Sort to sort the elements efficiently.
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).
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With