import java.util.*; // need for sort public class SearchComparableArray { public static void main(String[] args) { int length = Integer.parseInt(args[0]); Integer key = new Integer(args[1]); Comparable[] a = new Comparable[length]; for (int i = 0; i < a.length; i++) a[i] = MyMath.randInteger(1,10); print(a); Arrays.sort(a); // need sorting for binary search print(a); System.out.println("Linear search "+linearSearch(a,key)); System.out.println("Binary search "+binarySearch(a,key)); } // linear search on possibly unsorted array: public static boolean linearSearch(Comparable[] a,Object k){ int i = 0; while (i < a.length) if (a[i].compareTo(k)==0) return true; else i++; return false; } // binary search on sorted array // left and right are the two end points of interval: public static boolean binarySearch(Comparable[] a, Object k){ int left = 0; int right = a.length - 1; int middle; while (left <= right) { middle = (left + right)/2; switch(a[middle].compareTo(k)) { case 0: return true; case 1: right = middle-1; break; case -1: left = middle+1; break; default: return false; } } // if we reach here, we didn't find the object: return false; } // display array: public static void print(Comparable[] a) { for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } System.out.println(); } } class MyMath { // Return a random int between low and high, inclusive: public static int randInt(int low, int high) { return (int) (Math.random()*(high-low+1)) + (int) low; } public static Integer randInteger(int low, int high) { return new Integer(randInt(low,high)); } }