Advertisement
scottashipp

BadBinarySearch

Feb 13th, 2014
912
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.68 KB | None | 0 0
  1. public class BadBinarySearch {
  2.    
  3.     public static int rank(char key, char[] a) {
  4.         int lo = 0;
  5.         int hi = a.length - 1;
  6.         while (lo <= hi) {
  7.             // Key is in a[lo..hi] or not present.
  8.             int mid = lo + (hi - lo) / 2;
  9.             System.out.print("\t" + mid);
  10.             if      (key < a[mid]) hi = mid - 1;
  11.             else if (key > a[mid]) lo = mid + 1;
  12.             else return mid;
  13.         }
  14.         return -1;
  15.     }
  16.    
  17.    
  18.     public static void main(String[] args) {
  19.         char[] b = {'a','b','c','d','e'};
  20.         System.out.println("Searching for " + 'b');
  21.         int found = rank('b',b);
  22.         System.out.println("\n\nFound at " + found + "\n");
  23.     }
  24.  
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement