二分查找法

二分查找法,入参是需对数组进行排序


public class BinarySearch {

/**
* 二分查找
* @param key
* @param a
* @return
*/
public static int getKeyIndex(int key,int[] a) {

int low = 0;
int high = a.length-1;

while(low<=high) {
//被查找的key要么不存在,要么必然存在于a[0]和a[a.length-1]之间
int middle = low+(high-low)/2;
if(keyhigh = middle - 1;
}else if(key>a[middle]) {
low = middle+1;
}else {
return  middle;
}
}
return -1;
}


}

你可能感兴趣的:(算法学习)