2nd test case not working

#include
using namespace std;
int find_key(int a[],int n,int key){

int s=0;
int e=n-1;

while(s<=e){
int mid =(s+e)/2;

if(a[mid]==key){
    return mid;
}

else if(a[s]<=a[mid]){
    if(a[s]>=key and a[mid]>=key)
        e=mid-1;
    else
        s=mid+1;
}

else{
    if(a[mid]<=key and a[e]>=key)
    s=mid+1;
    else
    e=mid-1;
}

}
return -1;
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}

int key;
cin>>key;
cout<<find_key(a,n,key)<<endl;
return 0;
}

debug for this:
5
3
4
5
1
2
2
Correct output:
4
Your output:
-1

suggest me what i can do

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]