public class Java_A23 {
public static void main(String[] args) {
int a[] = {1,3,5,7,8,11,15,17,24,25,31,38,40,56,61,65,78,82,100};
int size = a.length;
int left, right, middle;
left = 0;
right = size - 1;
int test = 58; //要找的数
boolean ok = false;
for(;true;) {
middle = (left + right)/2;
if (a[middle] == test) {
left = middle;
right = middle;
ok = true;
break;
}
else {
if(a[left] < test && a[right] > test && left == right -1) {
ok = false;
break;
}
else {
if(a[middle] > test) {
right = middle;
}
else {
left = middle;
}
}
}
}
if(ok) {
System.out.println("找到这个数了,在数组的第" + (middle+1) + "个位置上。");
}
else {
System.out.println("找不到这个数,要找的数范围在数组的第" + (left+1) +"个数和第" + (right+1) + "个数之间");
}
}
}
Java 找数组中的元素
最新推荐文章于 2022-05-08 13:27:06 发布