/** * Some sample code for searching arrays. */ public class Searching { /** * Returns true if item is found somewhere in the input * array, false otherwise. This is an example of linear * search -- we search "in a straight line" from one end * of the array to the other. * * We decided that it would take N calls to ==, worst case, * to search for an item in an array of size N. Best case, * it might only take 1. Average could be more like N/2. * * @param data The array we're searching * @param key The item we're searching for * @return True if item is found */ public boolean contains(int[] data, int key) { for(int n : data) { if (n == key) { return true; } } return false; // We end up here if key isn't in data } /** * Returns the position in data at which key is found, or * -1 if it's not found. * * Analysis here was the same -- takes N == tests, worst * case, for an array of size N. * * @param data The array we're searching * @param key The item we're searching for * @return Index of key, or -1 */ public int indexOf(int[] data, int key) { for(int i=0; i 1) { System.out.println("Searching from position "+left+" to "+right); int mid = (left+right) / 2; // if(data[mid] == key) { // return true; // } if(key < data[mid]) { right = mid; } else { left = mid; } } System.out.println("Final box is at position "+left); return data[left]==key; // For now... } /** * To help us test the methods below */ public void test() { // int[] values = {9,3,7,10,8,12,10,15}; // System.out.println(contains(values, 10)); // System.out.println(contains(values, 2)); // System.out.println(contains(values, 15)); // System.out.println(indexOf(values, 10)); // System.out.println(indexOf(values, 2)); // System.out.println(indexOf(values, 15)); int[] ordered = {10,12,14,16,18,20,22,24,26,28,30}; // System.out.println(binarySearch(ordered, 24)); System.out.println(binarySearch(ordered,16)); System.out.println(binarySearch(ordered,10)); System.out.println(binarySearch(ordered,30)); System.out.println(binarySearch(ordered,13)); } }