2 回答
TA贡献1836条经验 获得超3个赞
您的问题称为“二分搜索”。为了使二分搜索工作,数组中的元素必须已经排序(这是您的情况,让我们假设升序)。二分查找首先将键与数组中间的元素进行比较:
如果key小于中间元素,则只需要在数组的前半部分继续查找key。
如果key大于中间元素,则只需要在数组的后半部分继续查找key。
如果键等于中间元素,则搜索以匹配结束。
所以二分查找法每次比较后至少消除数组的一半。假设您将在静态主函数中调用此方法:
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while(high >= low) { //search array until there is a single element left
int mid = (low + high) / 2; //mark middle index
if (key < list[mid]) //if key is smaller than the middle element..
high = mid - 1; //new high is the middle element
else if (key == list[mid]) //if key=middle element --> voila!
return mid; //returns the index of searched element if it is in your array
else
low = mid + 1; //if key is greater than the middle element new low is middle element
}
return –low - 1; //high < low, key not found
}
TA贡献1841条经验 获得超3个赞
像这样解决了:
while (true) {
if (targetint>array[array.length-1] || targetint<array[0])
return false;
int middleInt = array[Math.round(array.length/2)];
if (middleInt == targetint) {
return true;
} else if (targetint<middleInt) {
int[] firstHalf = new int[array.length/2];
System.arraycopy(array, 0, firstHalf, 0, firstHalf.length);
array = firstHalf;
} else if (targetint>middleInt) {
int[] secondHalf = new int[array.length/2];
System.arraycopy(array, array.length/2, secondHalf, 0, secondHalf.length);
array = secondHalf;
} else if(array.length == 1)
return false;
}
添加回答
举报