// Allison Obourn, CSE 142 // Examples of using arrays as parameters and returns import java.util.*; public class ArrayExamples { public static void main(String[] args) { int[] numbers = {11, 42, -5, 7, 27, 0, 89}; int[] numbers2 = {1, 43, 65, 0, 2, 54, 8}; System.out.println(Arrays.toString(numbers)); System.out.println(Arrays.toString(numbers2)); //reverse(numbers); // swap(numbers, 1, 3); //swapAll(numbers, numbers2); int[] merged = merge(numbers, numbers2); System.out.println(Arrays.toString(merged)); //System.out.println(Arrays.toString(numbers2)); } // Merges the three passed in arrays returning an array the size of // all three combined with a1's contents first followed by a2's and // finally a3's. public static int[] merge3(int[] a1, int[] a2, int[] a3) { // functional but long implementation /* int[] a4 = new int[a1.length + a2.length + a3.length]; for(int i = 0; i < a1.length; i++) { a4[i] = a1[i]; } // a1 = [1, 2, 4] for(int i = 0; i < a2.length; i++) { a4[i + a1.length] = a2[i]; } for(int i = 0; i < a3.length; i++) { a4[i + a1.length + a2.length] = a3[i]; } return a4; */ return merge(merge(a1, a2),a3); } // Takes two arrays and returns an array the size of both combined // with the contents of a1 at the beginning followed by a2's contents public static int[] merge(int[] a1, int[] a2) { int[] a3 = new int[a1.length + a2.length]; for(int i = 0; i < a1.length; i++) { a3[i] = a1[i]; } for(int i = 0; i < a2.length; i++) { a3[i + a1.length] = a2[i]; } return a3; } // takes two arrays of the same length and swaps their contents public static void swapAll(int[] a1, int[] a2) { for(int i = 0 ; i < a1.length; i++) { int temp = a1[i]; a1[i] = a2[i]; a2[i] = temp; } } // takes an array and two indecies. Swaps the elements in the // array stored at the two indecies. public static void swap(int[] a, int first, int last) { int temp = a[first]; a[first] = a[last]; a[last] = temp; } // takes an array and reverses it. 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; } } }