Context to mid point

why we are dividing the arrays into 2 parts and why we are calculating 2 mid point and in first part if we have found out the mid point then why we are searching the key in this region( a[start]<=key<=a[mid] )why we cannot
use another region (a[mid]<=key<a[end]) is it necessary to do so.

Hey @vikash3303, to make you understand this question better can you please tell me this issue you are facing more elaborately? I am unable to understand the issue you are facing. So elaborate your issue as much as possible and you can also tell in hinglish also if you want to :grinning:

bhaiya is saying if the mid lies in the first part of the array then that part of array(a[s] to a[mid] is sorted rest are unsorted and in second option if we have mid in another part of the array then that part of array(a[mid] to a[end] is sorted rest are unsorted

Hey @vikash3303, read it carefully.
Talking straightly, 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.

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]