Eduardo Santos Eduardo Santos - 1 year ago 73
Java Question

Rearrange an array in minimum and maximum java

Given an array of

s, I want to rearrange it alternately i.e. first element should be minimum, second should be maximum, third second-minimum, fourth second-maximum and so on...

I'm completely lost here...

Answer Source

Another method that doesn't require the space of three separate arrays but isn't as complex as reordering in place would be to sort the original array and then create a single new array. Then start iterating with a pointer to the current i-th index of the new array and pointers starting at the 0-th index and the last index of the sorted array.

public class Foo {

    public static void main(String[] args) {
        // Take your original array
        int[] arr = { 1, 4, 5, 10, 6, 8, 3, 9 };
        // Use the Arrays sort method to sort it into ascending order (note this mutates the array instance)
        // Create a new array of the same length
        int[] minMaxSorted = new int[arr.length];
        // Iterate through the array (from the left and right at the same time)
        for (int i = 0, min = 0, max = arr.length - 1; i < arr.length; i += 2, min++, max--) {
            // the next minimum goes into minMaxSorted[i]
            minMaxSorted[i] = arr[min];
            // the next maximum goes into minMaxSorted[i + 1] ... but
            // guard against index out of bounds for odd number arrays
            if (i + 1 < minMaxSorted.length) {
                minMaxSorted[i + 1] = arr[max];