-
Notifications
You must be signed in to change notification settings - Fork 0
/
ss_binary_search.cpp
75 lines (65 loc) · 1.16 KB
/
ss_binary_search.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
67
68
69
70
71
72
73
74
75
#include <iostream>
#define NULL_VALUE -1
#define SIZE 100
using namespace std;
int binarySearch(int* arr, int x){
int start = 0;
int end = SIZE - 1;
while(start <= end){
int middle = (start + end) / 2;
if(arr[middle] > x){
end = middle - 1;
}
else if(arr[middle] < x){
start = middle + 1;
}
else{
return middle;
}
}
return NULL_VALUE;
}
int binarySearchTwisted(int* arr, int x){
int origStart = 0;
int middle = 0;
int prev = arr[0];
int i = 1;
int l_arr = SIZE;
while(i < l_arr){
if(arr[i] < prev){
break;
}
prev = arr[i];
i += 1;
}
origStart = i;
int start = 0;
int end = SIZE - 1;
while(start <= end){
middle = (start + end) / 2;
if(arr[(middle + origStart) % l_arr] > x){
end = middle - 1;
}
else if(arr[(middle + origStart) % l_arr] < x){
start = middle + 1;
}
else{
return (middle + origStart) % l_arr;
}
}
return NULL_VALUE;
}
int main(){
int arr[SIZE];
for(int i=50; i<SIZE; i++){
arr[i] = i;
cout << arr[i] << endl;
}
for(int i=0; i<50; i++){
arr[i] = i;
cout << arr[i] << endl;
}
cout << "binarySearchTwisted" << endl;
cout << binarySearchTwisted(arr, 100) << endl;
return 0;
}