二分查找源码:
package com.company;
public class Main<nums> {
public static void main(String[] args) {
// write your code here
int[] nums = {2,1,5,4,2,13,20,7};
int flag = Binary_Search(nums,20);
System.out.println(flag);
}
//二分查找,输出数值数组下标
public static int Binary_Search(int[] nums,int key){
int low = 0;
int high = nums.length - 1;
while(low < high){
int mid = (low + high)/2;
if(nums[mid] < key)
low = mid + 1;
else if (nums[mid] > key)
high =mid - 1;
else
return mid;
}
return -1;
}
}
分析:
如果该键存在数组中,则返回它的索引,否则返回-1;
算法使用两个变量 low 和 high,并保证如果该建在数组中,则它一定在nums[low..........high]中,进入一个循环,将key不断与中间键(索引为 mid)作比较
①key==nums[mid] 返回mid
②key>nums[mid] 则low = mid +1
③key<nums[mid] 则high = mid - 1
④key != nums[low......high] 则return -1