I'm trying to find 1 in the array and getting -1. help me with the code in rotated sorted array

43 views Asked by At

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.

1

There are 1 answers

2
Renjith On

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

public static int search(int[] nums, int target) {
    int start = 0;
    int end = nums.length - 1;

    while (start <= end) {
        int mid = start + (end - start) / 2;

        if (nums[mid] == target) {
            return mid;
        }

        if (nums[start] <= nums[mid]) { // Left side is sorted
            if (target >= nums[start] && target < nums[mid]) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        } else { // Right side is sorted
            if (target > nums[mid] && target <= nums[end]) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
    }

    return -1;
}

public static void main(String[] args) {
    int[] arr = {3,4,5,6,7,0,1,2};
    int target = 1;
    int index = search(arr, target);
    System.out.println("Index of " + target + " is " + index);
}