// Marty Stepp, CSE 142, Spring 2010 // This program demonstrates a method to reverse an array. // Its purpose is to demonstrate array parameters and reference semantics. import java.util.*; // for Arrays class public class Reverse { public static void main(String[] args) { // index 0 1 2 3 4 5 int[] numbers = {11, 42, -5, 27, 0, 89}; // desired contents after call: // {89, 0, 27, -5, 42, 11} // swap 0 - 5 // swap 1 - 4 // swap 2 - 3 // ... reverse(numbers); System.out.println("The array is " + Arrays.toString(numbers)); reverse(numbers); System.out.println("The array is " + Arrays.toString(numbers)); // demonstrate making a copy so the original won't be damaged int[] numbers2 = Arrays.copyOf(numbers, numbers.length); Arrays.sort(numbers2); System.out.println("The array 2 is " + Arrays.toString(numbers2)); System.out.println("The array 1 is " + Arrays.toString(numbers)); } // Rearranges the elements of the given array into reverse order. // Example: [10, 20, 30, 40] -> [40, 30, 20, 10] public static void reverse(int[] numbers) { for (int i = 0; i < numbers.length / 2; i++) { swap(numbers, i, numbers.length - 1 - i); } } // Swaps the elements at the given two indexes. // Example: ([10, 20, 30, 40], 0, 2) -> [30, 20, 10, 40] public static void swap(int[] a, int index1, int index2) { int temp = a[index1]; a[index1] = a[index2]; a[index2] = temp; } /* // longer version that doesn't call swap public static void reverse(int[] numbers) { for (int i = 0; i < numbers.length / 2; i++) { int temp = numbers[i]; numbers[i] = numbers[numbers.length - 1 - i]; numbers[numbers.length - 1 - i] = temp; } } */ }