ArrayDemo.java

Download ArrayDemo.java

 1: // Demo to reverse an array of Strings in-place (without using a
 2: // second array); an idea taken from
 3: // <https://www.java67.com/2016/01/java-program-to-reverse-array-in-place.html>.
 4: // Written 10/2020 by Wayne Pollock, Tampa Florida USA
 5: 
 6: import java.util.Arrays;
 7: 
 8: class ArrayDemo {
 9:     public static void main ( String[] args ) {
10:         String[] data = { "Moe", "Larry", "Curly", "Shemp" };
11:         System.out.println( "Original Array:" );
12:         System.out.println( Arrays.toString(data) );
13:         reverse( data );
14:         System.out.println( "Reversed Array:" );
15:         System.out.println( Arrays.toString(data) );
16:     }
17: 
18:     // Swap the end elements, then the second and second-to-end, etc.,
19:     // working toward the middle.  (Note a recursive solution might
20:     // be simpler.
21:     public static void reverse(String[] array) {
22:         if (array == null || array.length < 2) {
23:             return;
24:         }
25:         int len = array.length;
26:         for (int i = 0; i < len / 2; i++) {
27:             // Swap the i-th and the i-th-from-the-end elements:
28:             String temp = array[i];
29:             array[i] = array[len - 1 - i];
30:             array[len - 1 - i] = temp;
31:         }
32:     }
33: }