package com.xiaojiang.search;public class BinarySearch { public static void main(String[] args) {
int pos;
int[] a = new int[100];
for (int i = 0; i < a.length; i++) {
a[i] = i;
System.out.print(i+" ");
}
//BinarySearch bs = new BinarySearch();
pos = binary_search(a, 18);
System.out.println("\nthe position is :"+pos);
} // 二分查找排序
public static  int binary_search(int[] a, int x) {
int low, high, mid;
low = 0;
high = a.length - 1;
while (low <= high) {
mid = low + (high - low)/2;//疑问是这地方为什么不能用>>1
if (x < a[mid]) {
high = mid - 1;
} else if (x > a[mid]) {
low = mid + 1;
} else {
return mid;
}
} return -1;
}}
要毕业找工作了,今天实现了一下二分查找算法,想高效地实现,不知道为什么mid = low + (high - low)>>1写一直通不过,程序运行一直不出结果,cpu呼呼的响,估计是死循环了,但是mid = low + (high - low)/2写就可以了,求高手解答一下为什么?  疑惑中……Java算法二分查找搜索

解决方案 »

  1.   

    mid = low + (high - low)/2;//疑问是这地方为什么不能用>>1
    如果想使用移位运算,还是得先知道使用的优先度的
    既然是死循环,那么就是可以运算,只不过运算出来的结果出错,那么你其实就应该输出结果看结果,然后就知道原因了
    mid = low + (high - low)>>1改成
    mid = low + ((high - low)>>1)
      

  2.   

    System.out.println(12+11>>1);
    System.out.println(12+(11>>1));
    System.out.println((12+11)>>1);
    System.out.println(23>>1);