public class ArrayTest {
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6,7,8};
// 找到元素为 7 的下标
int index = binarrySeach(array,8);
System.out.println("下标为:"+ index);
}
private static int binarrySeach(int[] array, int flage) {
int begin = 0;
int end = array.length -1;
while (begin <= end) {
int mid = (begin+end) / 2;
if (array[mid] == flage) {
System.out.println("找到了该元素");
return mid;
} else if (array[mid] < flage) { //查找元素在右边
begin = mid + 1;
} else { //查找元素在左边
end = mid - 1;
}
}
System.out.println("没有找到该元素");
return -1;
}
}
Java 二分查找算法
最新推荐文章于 2024-08-05 22:19:07 发布