/** * This class contains methods implementing linear and binary search. * * @author Brad Richards * @version 1.1 */ public class Searches { private int counter = 0; // To count the number of comparisons /** * Returns the current value of the counter. * @return Counter's current value */ public int getCount() { return counter; } /** * Sets the counter back to zero */ public void clearCount() { counter = 0; } /** * Returns true if item is found somewhere in the input * array, false otherwise. * @param data The array we're searching * @param key The item we're searching for * @return True if item is found */ public boolean linearSearch(int[] data, int key) { for(int n : data) { counter = counter + 1; if (n == key) { // Found it! return true; } } // If we haven't returned yet, I guess the key // wasn't in the data. NOW it's time to fail: return false; } /** * Binary search requires that the input array be sorted (from * smallest to largest), and takes advantage of that to search * more efficiently: At each step of the search we look at the * midpoint of the "unsearched region" of the array and decide * whether the value we're looking for would be in the left half * or the right. * @param data The array we're searching * @param key The item we're searching for * @return True if item is found */ public boolean binarySearch(int[] data, int key) { int left = 0; int right = data.length; while (right-left > 1) { System.out.println("Trying to find "+key+" from "+left+" to "+right); int mid = (left+right)/2; System.out.println("Item at midpoint is "+data[mid]); /* counter = counter + 1; if (key == data[mid]) { // Did we find it at position mid? return true; } */ counter = counter + 1; if (key < data[mid]) { right = mid; } else { // >= case here left = mid; } } counter = counter + 1; return data[left]==key; } /** * Finds the median value in an array. It checks each value in the array to see * if there are an equal number of integers less than it and greater than it. * * @param data An array of ints, not necessarily ordered * @return The median value in the array if one exists */ public int findMedian(int[] data){ for(int i = 0; i < data.length; i++){ int lessThan = 0; // counts how many numbers are less than list[i] int grtThan = 0; // counts how many numbers are greater than list[i] for(int j = 0; j < data.length; j++){ if(data[j] < data[i]){ lessThan++; } else if(data[j] > data[i]){ grtThan++; } } // If length is odd, data[i] is median if same number of values < it as > if (data.length%2 == 1 && lessThan == grtThan) { return data[i]; } // If the list has even length, we'll settle for a slight mismatch else { if (data.length%2 == 0 && lessThan == grtThan-1) { return data[i]; } } } // If we end up here, there's no median return -1; } }