Java 1.1: swapping numbers in array using temporary value

javaSwapArray

public class Main {

    public static void main(String[] args) {

        int [] x = {4, 3, 2, 1};

        if ( x[0] > x[3] ) {
            int temp = x[0];
            x[0] = x[3];
            x[3] = temp;
        }

        System.out.println("Swapping [0] & [3], the array should be 1, 3, 2, 4.");

        System.out.println(">> Your code gives: "   + x[0] + ", "
                                                    + x[1] + ", "
                                                    + x[2] + ", "
                                                    + x[3]);

        if ( x[1] > x[2] ) {
            int temp = x[1];
            x[1] = x[2];
            x[2] = temp;
        }

        System.out.println("Swapping [1] & [2], the answer should be 1, 2, 3, 4.");

        System.out.println(">> Your code gives: "   + x[0] + ", "
                                                    + x[1] + ", "
                                                    + x[2] + ", "
                                                    + x[3]);

    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s