首页 热点资讯 义务教育 高等教育 出国留学 考研考公

二分搜索技术

发布网友 发布时间:2022-04-04 00:47

我来回答

2个回答

热心网友 时间:2022-04-04 02:16

public static void main(String[] args) {
int value = 19;
int[] array = new int[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int index =0 ,endIndex = array.length-1;
while(index < endIndex-1){
int temp = (endIndex-index+1)/2 + index;
System.out.println("array["+temp+"]="+array[temp]);
if(array[temp]<value){
index = temp+1;
}else if(array[temp]==value){
index = endIndex = temp;
break;
}else{
endIndex = temp;
}
}
System.out.println(array[(int)index]);
}

热心网友 时间:2022-04-04 03:34

public int binarySearch(int[] a, int searchKey) { int lowerBound = 0; int upperBound = a.length - 1; int curIn; while (true) { curIn = (lowerBound + upperBound) / 2; if (a[curIn] == searchKey) return curIn; else if (lowerBound > upperBound) return -1; else { if (a[curIn] < searchKey) lowerBound = curIn + 1; else upperBound = curIn - 1; } } }

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com