-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPivotOfAnArrayBinarySearch.cpp
52 lines (43 loc) · 1.42 KB
/
PivotOfAnArrayBinarySearch.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
/* PROGRAM TO FIND PIVOT INDEX OR EQUILLIBRIUM INDEX */
#include <iostream>
using namespace std;
// function to find pivot element of an array
int pivotElementOfAnArray(int array[], int size) {
// initialising value of start and end point of an array
int start = 0, end = size - 1, mid;
// binarySearch
while (start < end) {
/* mid index of array here we are not writing (s+e)/2 too handle a condition
where start and end both are 2^31-1 which will execeed the int range while adding */
mid = start + (end - start) / 2;
if (array[mid] >= array[0]) {
start = mid + 1;
} else {
end = mid;
}
}
return start;
}
// main function
int main() {
// array of size 20
int array[20];
/* initialising array with custom size
which user will enter */
int size;
// enter the size of array
cout << "Enter the size of array: ";
cin >> size;
// array of size entered by user
array[size];
// enter the array elements
cout << "Enter the array elements" << endl;
for (int i = 0; i < size; i++) {
cout << "\tEnter element at " << i << "th index: ";
cin >> array[i];
}
// result will store index of pivot of an array
int result = pivotElementOfAnArray(array, size);
cout << "Index of Pivot element " << result << " and element at this index: " << array[result] << endl;
return 0;
}