Search The Pivot Element Using Binary Search in A Sorted and Rotated Array

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

// search the pivot element using binary search in a sorted and rotated

array...................... time complexity O(log(n))

#include <iostream>
using namespace std;

int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int beg=0,end=n-1,p;
int mid=(beg+end)/2;
while(beg<=end){
if(arr[mid]>arr[mid+1]){
p=mid;
break;
}
else if(arr[mid]<arr[mid-1]){
p=mid-1;
break;
}
if(arr[mid]>arr[end]){
beg=mid+1;
mid=(beg+end)/2;
}
else if(arr[mid]<arr[end]){
end=mid-1;
mid=(beg+end)/2;
}
}
cout<<p;
}
return 0;
}

You might also like