-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPivot_in_rotated_array.cpp
More file actions
70 lines (57 loc) · 1.88 KB
/
Pivot_in_rotated_array.cpp
File metadata and controls
70 lines (57 loc) · 1.88 KB
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
67
68
69
70
// This project is built using the C++14 standard.
// find the pivot index in a rotated sorted array
// The pivot index is the index of the smallest element in the rotated sorted array.
// The array is rotated at some pivot unknown to you beforehand.
#include <iostream>
using namespace std;
// fisrt approach
// This approach uses a binary search to find the pivot index in a rotated sorted array.
// The pivot index is the index of the smallest element in the rotated sorted array.
int pivot(int arr[], int n) {
int i = 0, j = n - 1;
while (i <= j) {
int mid = i + (j - i) / 2;
// If mid is the pivot
if (arr[mid] < arr[j] && (mid == 0 || arr[mid] < arr[mid - 1])) {
return mid;
}
// If left part is sorted, pivot must be in the right part
if (arr[mid] >= arr[i]) {
i = mid + 1;
}
// Otherwise, pivot must be in the left part
else {
j = mid - 1;
}
}
return -1; // No pivot found
}
// second approach
// This approach uses a binary search to find the pivot index in a rotated sorted array.
// The pivot index is the index of the smallest element in the rotated sorted array.
int findPivot(int arr[], int n) {
int i = 0, j = n - 1;
while (i < j) {
int mid = i + (j - i) / 2;
if (arr[mid] > arr[j]) {
// Pivot must be in the right part
i = mid + 1;
} else {
// Pivot is in the left part, including mid
j = mid;
}
}
return i; // or j, since i == j
}
int main() {
int arr[] = { 15 , 16 ,17 , 18 , 14};
int n = sizeof(arr) / sizeof(arr[0]);
int pivotIndex = pivot(arr, n);
if (pivotIndex != -1) {
cout << "Pivot index: " << pivotIndex << endl;
} else {
cout << "No pivot found." << endl;
}
// Output: Pivot index: 4
return 0;
}