Advertisement
scottashipp

BadBinarySearch3

Feb 14th, 2014
922
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 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.             System.out.print("Lo: " + lo + "\tHi: " + hi);
  9.             int mid = (int)((lo + ((hi - lo) / 2.0) + 0.5));
  10.             System.out.println("\tMid: " + mid);
  11.             if      (key < a[mid]) hi = mid - 1;
  12.             else if (key > a[mid]) lo = mid + 1;
  13.             else return mid;
  14.         }
  15.         return -1;
  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("\nFound at " + found + "\n");
  23.         System.out.println("Searching for " + 'd');
  24.         found = rank('d',b);
  25.         System.out.println("\nFound at " + found + "\n");
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement