package com.algorithms;
public class BinarySearch {
/**
* numbers 有序数组
* key 被查找的元素
* return 未找到的话返回-1
* 算法复杂度O(logN)
**/
public static int keyPosition(int[] numbers,int key) {
int high=numbers.length-1;
int low=0;
while(low<=high){
int mid=low+(high-low)/2;
if (key>numbers[mid]) {
low=mid+1;
}else if (key<numbers[mid]) {
high=mid-1;
}else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(keyPosition(new int[]{1,2,3,4,5},3));
}
}
二分查找(java实现)
最新推荐文章于 2020-09-02 14:25:58 发布