/* This program generates 2 random 4-element arrays of int values 1..5, sorts them and compares the two arrays to * see which is less than the other. Arrays are compared based on earliest index. For instance, the sorted array * 1, 1, 2, 5 < 1, 1, 3, 4 because 2 < 3. */ import java.util.*; // for Arrays and Random public class ArrayComparison { public static void main(String[] args) { Random g = new Random(); int[] array1, array2; array1 = getArray(g); // auto-generate the array of 4 elements, note that duplicates are allowed array2 = getArray(g); Arrays.sort(array1); Arrays.sort(array2); int result = compare(array1,array2); // compare the two arrays and output the results if(result<0) System.out.println(output(array1) + " is less than " + output(array2)); else if(result>0) System.out.println(output(array2) + " is less than " + output(array1)); else System.out.println("The two arrays are identical: " + output(array1) + " " + output(array2)); } // randomly generate 4 int values from 1..5 inserting them into an array and return the array public static int[] getArray(Random g) { int[] temp = new int[4]; for(int i=0;i<4;i++) temp[i] = g.nextInt(5)+1; return temp; } // iterate down both arrays comparing elements, if a1[0] < a2[0] then a1 < a2, if a1[0] > a2[0] then a1 > a2, otherwise // a1[0] == a2[0] and so move on to the next elements (a1[1], a2[1]) to compare. If you make it through all 4 elements // and they are all equal, the two arrays are equal. Return -1 for a1 < a2, +1 for a1 > a2 and 0 if a1 == a2. public static int compare(int[] a1, int[] a2) { for(int i=0;i<4;i++) if(a1[i]