[英]How to use binary search when the array has odd value?
I'm using binarySearch
and it's worked well with arrays that has even index, but when the array has odd index (length) it's give wrong result. 我正在使用binarySearch
,它与具有偶数索引的数组一起使用时效果很好,但是当数组具有奇数索引(长度)时,它将给出错误的结果。
What i'v done so fare: 我这样做的票价:
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return - 1;
}
Input: 输入:
int[] arr1 = {5, 6, 8, 9, 11, 12, 11, 50, 1, 3, 15, 121, 33, 16, 17, 18, 19};
int[] arr2 = {5, 6, 8, 9, 11, 12, 11, 50, 1, 3, 15, 121, 33, 16, 17, 18};
Case: 案件:
System.out.println(binarySearch(arr1, 12));
System.out.println(binarySearch(arr2, 12));
OutPut: 输出:
-1
5
How i can get the right outPut in the both situation? 在两种情况下我如何都能获得正确的输出?
Binary search only works on sorted array 二进制搜索仅适用于排序数组
Solution : add Arrays.sort(list) 解决方案:添加Arrays.sort(list)
public static int binarySearch(int[] list, int key) {
Arrays.sort(list);
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid]) high = mid - 1;
else if (key == list[mid]) return mid;
else low = mid + 1;
} return - 1;
}
You must sort the arrays before doing binary search operation. 在执行二进制搜索操作之前,必须对数组进行排序。
In your question you are unable to search for the odd array length. 在您的问题中,您无法搜索奇数数组长度。
In java its very easy. 在Java中,它非常容易。
You can use the below code. 您可以使用以下代码。
import java.util.Arrays; class BS { public static void main(String args[]) { int[] arr1 = {5, 6, 8, 9, 11, 12, 11, 50, 1, 3, 15, 121, 33, 16, 17, 18, 19}; System.out.println(Arrays.binarySearch(arr1 , '12')); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.