/** * Implements binary search over an unordered list * Hence, the code needs to backtrack when it cannot find the target. * Generally, this is a really silly thing to do **/ public class BacktrackingSearch { /** * The data to be searched **/ private int[] data = {1, 998, 10, 997, 11, 996, 100, 995, 101, 994, 110, 993, 111, 992, 1000}; /** * A counter of the number of steps the search required **/ private int steps; /** * Default constructor ... nothing to do **/ public BacktrackingSearch() { } /** * The public searhc method. * Thsi sets private variable steps to 0, then begins a search. * Note that steps will be incorrect is there are two concurrent searches. **/ public boolean search(int target) { steps=0; return iSearch(target, 0, data.length-1, 1); } /** * Implement Binary search, recursively on internal array of ints * @param target the item to be found * @param lo the bottom of the range being searched * @param hi the top of the range being searched * @param depth the depth of the stack * @return true if the target was found */ private boolean iSearch(int target, int lo, int hi, int depth) { // increment steps. Every class to iSearch increments ... steps++; System.out.print(steps); // a base case. if (lo>hi) { System.out.println(); return false; } int mid = (lo+hi)/2; // Print information about what is being searched System.out.println(" " + target + " " + data[mid] + " " + lo + " " + hi + " " + depth); // Found it!! if (data[mid]==target) return true; // Check the upper half of the items to be searched if (iSearch(target, mid+1, hi, depth+1)) { return true; } else { // if the number was not in the upper half, check the lower half return iSearch(target, lo, mid-1, depth+1); } } public static void main(String[] args) { BacktrackingSearch bs = new BacktrackingSearch(); int[] tgts = {10}; for (int ii : tgts) System.out.println(bs.search(ii) ? "Found" : "Not Found"); } }