Search code examples
javaarrayssortingindices

sort an array, so that first and last element will form a "pair"


I have an array of objects which I want to sort by indices in the following order. I will always have an array size to the power of 2.

Example array size: 8. Indices: [0][1] [2][3] [4][5] [6][7]

After sort: [0][7] [1][6] [2][5] [3][4]

So basically alternating between first and last element which was not sorted yet.

I already thought of a way of doing it, and I can get the "pairs" but they are in the wrong order (and I think it would not work with any other to the power of 2 array?). Here I'm using an int array and their indices as values to make it simpler for myself.

int[] array = new int[]{0,1,2,3,4,5,6,7};
int[] sortedArray = new int[8];
for(int i = 0; i < array.length; i+=2){
    sortedArray[i] = array[i];
}
for(int i = 1; i < array.length; i+=2){
    sortedArray[i] = array[array.length - i];
}

Output: [0][7] [2][5] [4][3] [6][1]


Solution

  • You can do this with a single loop. Consider the following algorithm:

    int[] array = new int[]{0,1,2,3,4,5,6,7};
    int[] sortedArray = new int[8];
    for(int i = 0; i < array.length; i+=2){
        sortedArray[i] = array[i/2];
        sortedArray[i + 1] = array[array.length - i/2 - 1];
    }
    System.out.println(Arrays.toString(sortedArray)); // prints [0, 7, 1, 6, 2, 5, 3, 4]
    

    This creates the final array by setting two values at a time:

    • every even index of the result array is mapped with the first values of the initial array
    • every odd index of the result array is mapped with the last values of the initial array