相对于顺序查找,二分查找的要求比较高,它要求待查找的记录必须是有序的,并且必须采用顺序存储,二分查找一般只能应用于静态查找。
代码如下:
import org.junit.Test;
public class BinarySearch {
@Test
public void test() {
int[] arr = { 2, 4, 6, 8, 9,11 };
int res = binarySearch(arr, 9);
if (-1 == res) {
System.out.println("查找失败!");
} else {
System.out.println("查找成功,下标为" + res);
}
}
public int binarySearch(int[] arr, int e) {
int low = 0, high = arr.length, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == e)
return mid;
else if (arr[mid] < e)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
}