I'm a bit confused on how to sort this array using the following conditions:
int[] array = { 3, 15, 7, 11, 6, 4, 1, 8, 10, 13 };
The conditions are as follows:
- The largest integer is first
- The second-largest integer is last
- The third-largest integer should be second
- The pattern continues, leaving the smallest number in the middle.
For example, if the starting array is {1, 2, 3, 4, 5, 6, 7}, then the sorted array should be {7, 5, 3, 1, 2, 4, 6}.
Any help with this? I'm new to sorting algorithms, so I'm still trying to figure out the logic I should walk myself through to do something like this. Thanks in advance!
CodePudding user response:
Maybe this solution copy the array too many times, but it works.
package at.ylz.playground;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// int[] array = {3, 15, 7, 11, 6, 4, 1, 8, 10, 13};
int[] array = {1, 2, 3, 4, 5, 6, 7};
var sortedArray = Arrays.stream(array).boxed().sorted(Collections.reverseOrder()).mapToInt(value -> value).toArray();
int n = array.length;
int[] res = new int[n];
int left = 0, right = n-1;
while (left <= right) {
res[left] = sortedArray[left*2];
if(left*2 1<n)
res[right] = sortedArray[left*2 1];
left ;
right--;
}
for (int i : res) System.out.println(i);
}
}