-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbsearch.cpp
52 lines (42 loc) · 1.05 KB
/
bsearch.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
#include <iostream>
#include <limits>
#define INVALID_VALUE std::numeric_limits<std::size_t>::max()
using std::cout;
constexpr std::size_t operator "" _z (unsigned long long size)
{
return size;
}
template<typename Data>
size_t iterativeBinarySearch(Data array[], std::size_t size, Data value)
{
// Use the same type to avoid conversion and truncation
// and handle the biggest possible sizes of arrays on given platform
size_t start = 0;
size_t end = size - 1;
size_t debugCounter = 0;
while (start <= end)
{
debugCounter++;
cout << debugCounter << "\n";
size_t mid = (start + end) / 2_z; //std::size_t{2};
if (array[mid] == value)
{
return mid;
}
else if (array[mid] > value)
{
end = mid - 1;
}
else if (array[mid] < value)
{
start = mid + 1;
}
}
return INVALID_VALUE;
}
int main()
{
int array[] = {1, 4, 5, 3, 3, 4};
cout << iterativeBinarySearch(array, 6, 3) << " is the searched position of number!" << "\n";
return 0;
}