其他分享
首页 > 其他分享> > 练习

练习

作者:互联网

package com.yingyong.day13;

public class MiddleFind {

public static void main(String[] args) {
// TODO Auto-generated method stub
int [] arr3 = new int[] {-99,-54,-2,0,2,33,43,256,999};
boolean isFlag = true;
int number = 256; //int number = 25;
int head = 0; //首索引位置
int end = arr3.length - 1; //尾索引位置
while(head <= end) {
int middle = (head + end) / 2;
if(arr3[middle] == number) {
System.out.println("找到指定元素,索引为:" + middle);
isFlag = false;
break;
}else if(arr3[middle] > number) {
end = middle - 1;
}else {//arr3[middle] + number
head = middle + 1;
}

}
if(isFlag) {
    System.out.println("未找到指定元素");
}

}
}
结果:找到指定元素,索引为:7

标签:索引,int,练习,isFlag,number,middle,arr3
来源: https://blog.51cto.com/14980927/2562885