import java.util.Arrays; public class ArrayPractice { public static void main(String[] args) { int[] a = {10, 20, 30, 40}; System.out.println("Before: " + Arrays.toString(a)); swap1st2nd(a); System.out.println("After: " + Arrays.toString(a)); a = new int[]{10, 20, 5, 30, 40}; System.out.println("Before: " + Arrays.toString(a)); swap1st2nd(a); System.out.println("After: " + Arrays.toString(a)); a = new int[0]; // empty array System.out.println("Before: " + Arrays.toString(a)); swap1st2nd(a); System.out.println("After: " + Arrays.toString(a)); } /* * Write a method that takes an array of integers * and that swaps the first and second halves of the array * if the array is [1, 3, 10, 20] * the method would change it to * [10, 20, 1, 3] * and if the array is [1, 3, 5, 10, 20] * the method would change it to * [10, 20, 5, 1, 3] * * you can't use another array or an array list in * your solution */ public static void swap1st2nd(int[] a) { // loop over the first half for (int i = 0; i < a.length/2; i ++) { // corresponding index in the second half int j = i + (a.length + 1) / 2; // swap a[i] and a[j] int temp = a[i]; a[i] = a[j]; a[j] = temp; } } }