Binary search on unsorted array?

How am i supposed to apply binary search on unsorted array??
It is written here that he doesnt have time to sort the array again, so how can we do this using binary search?

@bhavik911,

we have 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.

Here is the Algorithm that will let you find the element in O(log n)

  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] 

how are you checking whether arr[l, mid] is sorted or not?
or arr[mid+1,r] is sorted or not??

Also it is not given if initial arrray was ascending or descending

Is is necessary to use recursion in this ,as that topic has not been covered yet

@bhavik911,
you can check by:

 if (arr[l] <= arr[mid]) { 

@bhavik911,
It is a sorted array which is rotated. Something like:
if the sorted array is: 1 2 3 4 5

some examples of the rotated sorted array would be: 4 5 1 2 3 or 5 1 2 3 4

@bhavik911,
You can try using a while loop but it might complicate the code. Its suggested that you use recursion

@sanchit.bansal06 can please explain the pivot element approach how does it take 0(n)