java二分查找算法非递归代码实现
程序员文章站
2024-03-20 09:49:34
...
/**
* @author Drug
* @create 2020-05-12 14:02
*/
public class BinarySearchNoRecur {
public static void main(String[] args) {
int[] arr = {0,1,3,15,17,22,100,230,1512};
int i = binarySearch(arr, 101);
System.out.println(i);
}
/**
* 二分查找
* @param arr
* @param value
* @return
*/
public static int binarySearch(int[] arr, int value){
int left = 0;
int right = arr.length - 1;
int mid;
while(left <= right){
mid = (left + right) / 2;
if(arr[mid] == value){
return mid;
}else if(arr[mid] > value){
//向左边二分
right = mid - 1;
}else{
//向右边二分
left = mid + 1;
}
}
return -1;
}
}
上一篇: iOS MD5和SHA1加密
下一篇: uva 12412