-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathminimum_in_rotated_sorted_array.cpp
66 lines (55 loc) · 1.4 KB
/
minimum_in_rotated_sorted_array.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Given a sorted and rotated array.
The array is rotated between 1 and n times[ n = array size]
find the minimum element of the input array.
array may contain duplicate elements.
*/
#include <bits/stdc++.h>
using namespace std;
int get_minimum_element(int ar[], int N)
{
int first = 0, last = N - 1;
int minelement = -1;
while(first < last)
{
//if ar[first] > ar[last] then we will increment first and last remains same
if(ar[first] > ar[last])
{
first++;
minelement = ar[last];
}
//if ar[first] <= ar[last] then we will decrement last and first remains same
if(ar[first] <= ar[last])
{
last--;
minelement = ar[first];
}
}
return minelement;
}
int main()
{
cout << "Enter the size of the array : \n";
int N;
cin >> N;
int ar[N + 1];
cout << "Enter array elements :\n";
for (int i = 0; i < N; i++)
{
cin >> ar[i];
}
int minimum_element = get_minimum_element(ar, N);
cout << "Minimum Element of the array is: \n";
cout << minimum_element << endl;
}
/*
Standard Input and Output
Enter the size of the array :
12
Enter array elements :
465 7878 3535 68 3435 89897 466 878 44 7879 3 67868
Minimum Element of the array is:
3
Time Complexity : O( N )
Space Complexity : O(1)
*/