Reordering an array: Even elements descending, odd elements ascending I am trying to work out a solution. I have to order the elements in the array a,  such that a[0] is greater than a[1],  a[1] is less than a[2], a[2] is greater than a[3], and so on...

Basically my method checks if the index is odd or even , and simultaneously makes a decision to swap elements to suit the criteria of the question.

I am getting the following output: 7, 1, 6, 2, 5, 3, 4

public class ArrayRearrange {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = { 2, 1, 4, 6, 5, 3, 7 };

        for (int i = 0; i &lt; a.length; i++) {
            for (int j = i + 1; j &lt; a.length; j++) {
                if (i % 2 == 0 &amp;&amp; a[i] &lt; a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
                if (i % 2 != 0 &amp;&amp; a[i] &gt; a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        for(int i=0;i&lt;a.length;i++)
        System.out.print(a[i]+" ");

    }

}


Let me know if there's a better way to do it.
Putting everything in the main method is bad practice, and is hard to maintain. Separate it into methods. This also removes duplicate code, such as when you swap values.
// TODO Auto-generated method stub is generated in eclipse, and is only there to remind you to finish the method. It is not really to stay.
Don't use one-letter variable names, except for counters. a should be array.
Don't be lazy when you print something out. Still follow conventions.
The two if statements are doing identical things. Combine them with an OR.


Final code:

public class ArrayRearrange {

    public static void main(String[] args) {
        int[] array = { 2, 1, 4, 6, 5, 3, 7 };

        rearrange(array);

        for(int i = 0; i&lt;array.length; i++) {
            System.out.print(a[i] + " ");
        }
    }

    private static void rearrange(int[] array) {
        for (int i = 0; i &lt; array.length; i++) {
            for (int j = i + 1; j &lt; array.length; j++) {
                if ((i % 2 == 0 &amp;&amp; array[i] &lt; array[j]) || (i % 2 != 0 &amp;&amp; array[i] &gt; array[j])) {
                    swap(array, i, j);
                }
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

}