Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search an element in sorted but rotated array #605

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions pivot_search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <bits/stdc++.h>
using namespace std;
int getpivot(int arr[],int n)
{
int s=0;
int e=n-1;
int mid=s+(e-s)/2;
while(s<e)
{
if(arr[mid]>=arr[0])
{
s=mid+1;
}
else
{
e=mid;
}
mid=s+(e-s)/2;
}
return s;
}
int main() {
vector<int> arr;
int n;
cout<<"Enter the size of the array : ";
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int key;
cout<<"Enter element to be searched : ";
cin>>key;
int pivot=getpivot(arr,6);
if(arr[pivot]>key)
int pos=binary_search(arr.begin(),arr+pivot,key);
else pos=binary_search(arr+pivot,arr.end());
if(pos==-1)
{
cout<<"Element not found!";
}
else
{
cout<<"Element found at index "<<pos;
}
return 0;
}