I have an array in ascending order, consisting of positive integers and with condition duplicates are not allowed.In the array i must find m such that array[m]=m using binary search
I have used below code:
public class Main {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
int n = a.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = a.nextInt();
}
int result = binarysearch(arr,n);
if(result!=-1)
System.out.println(result);
else
System.out.println("NOT_FOUND");
}
public static int binarysearch(int[] array,int n){
int start=1,end=n;
while(start<=end){
int mid = (start+end)/2;
if(mid==array[mid-1])
return mid;
else if(mid<array[mid-1])
end=mid-1;
else
start=mid+1;
}
return -1;
}
Please note that the array is 1-indexed and not 0-indexed
The problem I am facing is when i try the following case : array={1,2,3,4,5}
the expected output is 1
but due to binary search the method returns 3 as Output.
Is there any workaround to bypass this type of cases?