Reverse.java


Below is the syntax highlighted version of Reverse.java from §2.1 Static Methods.


/******************************************************************************
 *  Compilation:  javac Reverse.java
 *  Execution:    java Reverse args1 args2 args3
 *
 *  % java Reverse Alice Bob Carol Dan
 *  args[]
 *  ---------------------------------------
 *  Alice
 *  Bob
 *  Carol
 *  Dave
 *
 *  Array returned by reverse1(args)
 *  ---------------------------------------
 *  Dave
 *  Carol
 *  Bob
 *  Alice
 *
 *  args[] did not change
 *  ---------------------------------------
 *  Alice
 *  Bob
 *  Carol
 *  Dave
 *
 *  args[] after calling reverse2(args)
 *  ---------------------------------------
 *  Dave
 *  Carol
 *  Bob
 *  Alice
 *
 ******************************************************************************/

public class Reverse {

    // swap a[i] and a[j]
    public static void exch(String[] a, int i, int j) {
        String swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }

    // return a new array that contains the entries in the argument array in reverse order
    public static String[] reverse1(String[] a) {
        int n = a.length;
        String[] reverse = new String[n];
        for (int i = 0; i < n; i++) {
            reverse[i] = a[n-i-1];
        }
        return reverse;
    }

    // reverses the entries in the array
    public static void reverse2(String[] a) {
        int n = a.length;
        for (int i = 0; i < n/2; i++) {
            exch(a, i, n-i-1);
        }
    }

    // print the entries in the array a[] to standard output
    public static void show(String[] a) {
        for (int i = 0; i < a.length; i++) {
            StdOut.println(a[i]);
        }
    }

    public static void main(String[] args) {

        // original array
        StdOut.println("args[]");
        StdOut.println("---------------------------------------");
        show(args);
        StdOut.println();

        // create a new array that is the reverse of args[]
        StdOut.println("Array returned by reverse1(args)");
        StdOut.println("---------------------------------------");
        String[] reverse = reverse1(args);
        show(reverse);
        StdOut.println();

        // args[] did not change
        StdOut.println("args[] did not change");
        StdOut.println("---------------------------------------");
        show(args);
        StdOut.println();

        // args[] after calling reverse2(args)
        StdOut.println("args[] after calling reverse2(args)");
        StdOut.println("---------------------------------------");
        reverse2(args);
        show(args);
        StdOut.println();
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:15:13 EDT 2022.