二分查找

public class Test5 {
public static void main(String[] args) {
int[] nums={0,1,2,3,4,5,6,7,8,9};
//0,1,2,3,4, 中间元素 5,6,7,8,9
//5,6, 7, 8,9
//8, 9
//9

int keys=9;//寻找7

int startIndex=0;
int endIndex=nums.length-1;
int midIndex=-1;//假设为-1表示未找到
boolean flag=false;

do {
midIndex = (endIndex + startIndex) / 2;
if (keys == nums[midIndex]) {//中间的数据 刚好为目标书
System.out.println("you find data at index=" + (midIndex + 1) );
flag=true;
} else if (keys > nums[midIndex]) {//目标书 > 中间的数据
startIndex = midIndex + 1;
} else {////目标书 < 中间的数据
endIndex = midIndex - 1;
}
}while(startIndex<=endIndex && !flag);
}
}
posted @ 2021-11-13 21:17  学代码的cc  阅读(28)  评论(0)    收藏  举报