// This class contains several small examples of array manipulation. // Each is written as a method. import java.util.*; public class ArraySample3 { public static void main(String[] args) { int[] list1 = {12, 8, 4, 0, 208, 14, 42, 38, 72, 96, 102}; int[] list2 = {84, 42, 92, 96, 2, 4, 8, 0, 72, 302, 17, 408}; testAll(list1); testAll(list2); } public static void testAll(int[] list) { System.out.println("list = " + Arrays.toString(list)); System.out.println("allEven returns " + allEven(list)); System.out.println("indexOf(42) returns " + indexOf(list, 42)); System.out.println("indexOf(16) returns " + indexOf(list, 16)); int[] sum = runningSum(list); System.out.println("running sum = " + Arrays.toString(sum)); sort(list); System.out.println("sorted list = " + Arrays.toString(list)); System.out.println(); } // returns true if all integers in the given list are even, returns false // otherwise public static boolean allEven(int[] list) { for (int i = 0; i < list.length; i++) { if (list[i] % 2 != 0) { return false; } } return true; } // returns the index of the first occurrence of the given value in the // given list; returns -1 if not found public static int indexOf(int[] list, int target) { for (int i = 0; i < list.length; i++) { if (list[i] == target) { return i; } } return -1; } // returns a new array that contains the running sum of the numbers in the // given list public static int[] runningSum(int[] list) { int[] result = new int[list.length]; if (list.length > 0) { result[0] = list[0]; for (int i = 1; i < list.length; i++) { result[i] = list[i] + result[i - 1]; } } return result; } // sorts the given list into nondecreasing order using insertion sort public static void sort(int[] list) { for (int i = 1; i < list.length; i++) { int value = list[i]; int j = i; while (j > 0 && value < list[j - 1]) { list[j] = list[j - 1]; j--; } list[j] = value; } } }