Advertisement
Guest User

Untitled

a guest
Apr 16th, 2012
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.43 KB | None | 0 0
  1. public class BinarySearch {
  2. /** Use binary search to find the key in the list */
  3. public static int binarySearch(int [] list, int key) {
  4. int low = 0;
  5. int high = list.length - 1;
  6.  
  7. while (high >= low) {
  8. int mid = (low + high) / 2;
  9. if (key < list[mid])
  10. high = mid - 1;
  11. else if (key == list[mid])
  12. return mid;
  13. else
  14. low = mid + 1;
  15. }
  16. return -low - 1; // Now high < low, key not found
  17. }
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement