forked from IOSD/Algo
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsorted_rotatedarray.cpp
More file actions
39 lines (31 loc) · 878 Bytes
/
sorted_rotatedarray.cpp
File metadata and controls
39 lines (31 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
using namespace std;
///program to find the pivot element in a sorted rotated array very efficiently using a optimised code
///time complexity= O(log(n))
///space complexity = O(1)
///method used = BINARY SEARCH
int main()
{
int n;int *arr;
cin>>n;
arr=new int[n]; //dynamic initialization of the array
for(int i=0;i<n;i++)
cin>>arr[i]; //input for the array
int s=0,e=n-1;int mid;
while(s<=e)
{
cout<<"pivot is at index ";
mid=(s+e)/2;
if((arr[mid]>arr[mid+1])&&(mid<e))
{cout<<mid;break;} ///checking for pivot element
if((arr[mid]<arr[mid-1])&&(mid>s))
{cout<<mid-1;break;}
if((arr[s]>=arr[mid]))
e=mid-1;
else
e=mid+1;
}
if(s>e)
cout<<"pivot does not exist";
return 0;
}