0% found this document useful (0 votes)
75 views1 page

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

This C++ code uses binary search to find the pivot element in a rotated sorted array in O(log(n)) time. It takes input of test cases t and size of each array n. It initializes pointers beg and end and finds the mid element. It compares mid with neighbors to find the pivot and breaks the while loop. Finally it prints the pivot index p.

Uploaded by

Nikhil Bajaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views1 page

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

This C++ code uses binary search to find the pivot element in a rotated sorted array in O(log(n)) time. It takes input of test cases t and size of each array n. It initializes pointers beg and end and finds the mid element. It compares mid with neighbors to find the pivot and breaks the while loop. Finally it prints the pivot index p.

Uploaded by

Nikhil Bajaj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 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