// Searching.java // Date: July 23, 2001 public class Searching { // Searches array a for item elt. If it's found, // return the index of elt; otherwise, return -1. // This method searches sequentially through the array. public static int sequential(int elt, int[] a) { // Loop from 1 to the length of a minus 1 for (int i = 0; i < a.length; i++) { // For each entry, check if it is the same as elt // If so, return the current index if (a[i] == elt) { return i; } } // If elt was not found, return -1 return -1; } // Searches array a for item elt. If it's found, // return the index of elt; otherwise, return -1. // This method performs a binary search, and assumes // that the input array is sorted in increasing order. public static int binary(int elt, int[] a) { int leftSide = 0; int rightSide = a.length-1; // Loop while left is less than right minus 1. // If this is not true, then we should check to // see if the elt is at either endpoint. while (leftSide < rightSide-1) { // Find the index in the middle of left and right int midIndex = (rightSide + leftSide)/2; // If elt equals the middle value, return the index if (elt == a[midIndex]) { return midIndex; } // If elt is bigger than the middle value, // move the left side in else if (elt > a[midIndex]) { leftSide = midIndex; } // Otherwise, move the right side in else { rightSide = midIndex; } } // end while if (elt == a[leftSide]) { return leftSide; } else if (elt == a[rightSide]) { return rightSide; } else { // If we get to this point, elt must not be in the array // so return -1 to indicate its absence. return -1; } } }