public class searchInRotatedSortedArray {
public static void main(String[] args) {
int[] arr = {3,4,5,6,7,0,1,2};
int target = 1;
int peak = peak_ele(arr);
int ans = bs(arr, target, 0, peak);
if (ans == -1) {
ans = bs(arr, target, peak+1, arr.length-1);
}
System.out.println(ans);
}
static int peak_ele(int[] arr){
int start=0;
int end=arr.length-1;
while(start<end){
int mid=start+(end-start)/2;
if(arr[mid]<arr[mid+1]){
start=mid+1;
}
else if(arr[mid]>arr[mid+1]){
end=mid;
}
}
return end;
}
static int bs(int[] arr, int target, int start, int end) {
while (start <= end) {
int mid = start + (end - start) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;
}
}
I was expecting to get the index of 1 in the array but I'm getting -1. The second half of array to find the target is not working idk. Help me find the error in the code as I have tried many times but I just couldn't figured it out.
Your program is wrong.You are finding the peak element and trying to do a binary search from start to end which will not work since the target could be anywhere in the array. If you are trying to search in a rotated array, try this