Help rahul to search - what is the error?

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for(int i = 0 ; i < n; i++){
arr[i] = scn.nextInt();
}
int m = scn.nextInt();
System.out.print(index(arr,m));

    // Your Code Here
}
public static int index(int[] arr,int m){
	int l = 0;
	int h = arr.length -1;
	while(l<=h){
	int mid = (l+h)/2;
	if( m > arr[mid]){
		l = mid + 1;
	}else if( m < arr[mid]){
		h = mid - 1;
	}else{
		return mid;
	}
	}
	return -1;


}

}

@asthaaggarwal2,

https://ide.codingblocks.com/s/222578 Corrected code.

Approach:

  1. Find middle point mid = (l + h)/2
  2. If the key is present at the middle point, return mid.
  3. Else If arr[l…mid] is sorted
  a) If the key to be searched lies in the range from arr[l] to 
     arr[mid], recur for arr[l..mid].
  b) Else recur for arr[mid+1..r]
  1. Else (arr[mid+1…r] must be sorted)
  a) If the key to be searched lies in the range from arr[mid+1]
     to arr[r], recur for arr[mid+1..r].
  b) Else recur for arr[l..mid] 

why it isnt a normal binary search ques?

@asthaaggarwal2,

the Question is to find an element in the Sorted but Rotated array. One can imagine this Question by finding the pivot element and then rotate it to get the original array and can use Binary search to find the element but the main point to consider is that:-

  • FInding the Pivot element in the array is of the O(n), so why would you do such a lot of work, if it is so then you can also use Linear Search which will let you find the element in O(n), Where n is the number of elements in the array.
  • But You would get TLE as the constraint is quite large.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.