'Binary search in array cannot find number correctly
Binary search is not working for number 5,3 and 7 in the array when I change the target value program shows no result.
package com.company;
public class Main {
public static void main(String[] args) {
int[] array = {8, 2, 5, 3, 4, 7, 6, 1,9};
int low=0;
int target=4;
int high=array.length-1;
while (low<=high){
int middle=low+(high-low)/2;
int value=array[middle];
System.out.println(middle);
if(value<target){
low=middle+1;
}
else if(value>target)
high=middle-1;
else
{
System.out.println("found "+middle);
break;
}
}
}
}
what do I need to change in code
Solution 1:[1]
The array must be sorted for binary search to work. Try adding Arrays.sort(array); right before the search. (Here's the documentation for that method.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fluffyyboii |
