日期:2014-05-20 浏览次数:20775 次
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;
}
}
System.out.println(12+11>>1);
System.out.println(12+(11>>1));
System.out.println((12+11)>>1);
System.out.println(23>>1);