算法-二分查找(非递归)
程序员文章站
2022-06-17 19:46:34
...
package com.chb.erfen;
public class binarysearch {
public static void main(String[] args) {
int a[]= {1,3, 8, 10, 11, 67, 100};
int index=search(a,10);
System.out.println(index);
}
public static int search(int[]arr,int value) {
int left=0;
int right=arr.length-1;
while(left<=right) {
int mid=(left+right)/2;
if(value==arr[mid]) {
return mid;
}else if(value<arr[mid]) {
right=mid-1;
}else {
left=mid+1;
}
}
return -1;//没找到返回-1
}
}
运行结果: