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.
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)
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.
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')); } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.