In this question i used linear search which has a complexity of O(n) but I cannot figure out how to use BFS here.
The logic i tried to use BFS was
Traverse through given array until we find an element which is arr[i+1]<arr[i]
Then till i use bfs from the point of starting array.
Then update the starting point and continue till we find our element below is the BFS code I tried .
How to do this que with binary search
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)
- Find middle point mid = (l + h)/2
- If the key is present at the middle point, return mid.
- 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]
- 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]
you can watch this too
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.