/*二分法的前提是这个数组是从大到小或者从小到大的排序方式,以下是按照从小到大的方式*/
public class Test {
public static void main(String[] args) {
// 定义一个数组
int nums[] = { 1, 3, 6, 8, 9, 10, 12, 18, 20, 33, 34 };
// 欲查询的数字
int num = 35;
// 输出num在nums中的索引
System.out.println(“二分法查看数组中某数的索引为:” + dichotomy(nums, num));
}
/**
* 二分法查找
*
* @param nums 数组
* @param num 查找的数
* @return 返回num索引,如果不存在返回-1
*/
public static int dichotomy(int[] nums, int num) {
// 数组长度必须大于零
if (nums != null && nums.length > 0) {
// 开始索引
int start = 0;
// 结束索引
int end = nums.length – 1;
// 中间索引
int center = (start + end) / 2;
// 开始索引不能大于结束索引
while (start <= end) {
// 取中间索引值比较,如果相同,返回该索引
if (num == nums[center]) {
return center;
}
// 如果值在center右边或左边,重新定位start或end,重新计算center值
if (num > nums[center]) {
start = center + 1;
}
if (num < nums[center]) { end = center - 1; } center = (start + end) / 2; } } return -1; } }