[关闭]
@lzb1096101803 2016-03-10T11:05:03.000000Z 字数 684 阅读 315

二分查找

电话面试


  1. package 二分查找;
  2. public class BinarySearch {
  3. public static int binarySearch(int key, int[] data){
  4. return binarySearch2(key, data, 0, data.length-1);
  5. }
  6. public static int binarySearch(int key, int[] data, int low, int height){
  7. if(low > height)
  8. return -1;
  9. int mid = (low + height) >>> 1;
  10. if(key > data[mid])
  11. return binarySearch(key, data, mid+1, height);
  12. else if(key < data[mid])
  13. return binarySearch(key, data, low, mid-1);
  14. else
  15. return mid;
  16. }
  17. public static int binarySearch2(int key, int[] data, int low, int height){
  18. while(low <= height){
  19. int mid = (low + height) >>> 1;
  20. if(key > data[mid])
  21. low = mid + 1;
  22. else if(key < data[mid])
  23. height = mid - 1;
  24. else
  25. return mid;
  26. }
  27. return -1;
  28. }
  29. public static void main(String[] args) {
  30. int[] data = {1,2,3,4,5,6,7,8,20};
  31. System.out.println(binarySearch(20, data));
  32. }
  33. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注