-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecursive_binary_search.cpp
More file actions
86 lines (71 loc) · 2.33 KB
/
recursive_binary_search.cpp
File metadata and controls
86 lines (71 loc) · 2.33 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
using namespace std;
int *slice(int array[], int from, int to)
{
int *newArray = new int[(to - from)];
for (int j = 0; j < (to - from); j++)
{
newArray[j] = array[from + j];
}
return newArray;
}
/* Returns either the index of the location in the array,
or -1 if the array did not contain the targetValue */
int doSearch(int array[], int arrayLength, int targetValue)
{
int min = 0;
int max = arrayLength - 1;
if (max < min)
{
return -1;
}
int guess = (arrayLength % 2 == 0) ? (arrayLength / 2) : ((arrayLength - 1) / 2);
if (targetValue > array[guess])
{
if (arrayLength == 2 && array[1] == targetValue)
{
return 1;
}
int temp = doSearch(slice(array, (guess + 1), arrayLength), (arrayLength - (guess + 1)), targetValue);
return (temp == -1) ? -1 : guess + 1 + temp;
}
if (targetValue < array[guess])
{
if (arrayLength == 2 && array[0] == targetValue)
{
return 0;
}
int temp = doSearch(slice(array, 0, guess), guess, targetValue);
return (temp == -1) ? -1 : temp;
}
return guess;
}
int main()
{
int primes[25] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
int result = doSearch(primes, 25, 73);
cout << "Found prime 73 at index " << result << endl;
cout << (result == 20 ? "True" : "False") << endl
<< endl;
result = doSearch(primes, 25, 13);
cout << "Found prime 13 at index " << result << endl;
cout << (result == 5 ? "True" : "False") << endl
<< endl;
result = doSearch(primes, 25, 89);
cout << "Found prime 89 at index " << result << endl;
cout << (result == 23 ? "True" : "False") << endl
<< endl;
result = doSearch(primes, 25, 43);
cout << "Found prime 43 at index " << result << endl;
cout << (result == 13 ? "True" : "False") << endl
<< endl;
result = doSearch(primes, 25, 10);
cout << "Found prime 10 at index " << result << endl;
cout << (result == -1 ? "True" : "False") << endl
<< endl;
result = doSearch(primes, 25, 120);
cout << "Found prime 120 at index " << result << endl;
cout << (result == -1 ? "True" : "False") << endl
<< endl;
}