Website Summary Files Commits Branches @commit @diff @stats
path: root / Seminar01 / src / searching-algorithms / binary-search.cpp
blob: 7404e0ad122665e0dd014630f439acf9a5fbc539 (plain) (blame)
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
#include <iostream>

template <class T>
int binarySearch(const T* arr, size_t size, T elem)
{
    int left = 0;
    int right = size - 1;

    while (right - left >= 0)
    {
        int mid = left + (right - left) / 2;

        if(arr[mid] == elem)
        {
            return mid;
        }
        else if (arr[mid] > elem)
        {
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }

    return -1;
}

constexpr unsigned EXAMPLE_SIZE = 7;

int main()
{
    int example[EXAMPLE_SIZE] = { 1, 2, 4, 8, 16, 32, 64 };
    int needle = 4;

    int index = binarySearch(example, EXAMPLE_SIZE, needle);
    if(index == -1)
    {
        std::cout << "Unable to find the element" << std::endl;
    }
    else
    {
        std::cout << "Element " << needle << " found at " 
            << index << " position: " << example[index] << std::endl; 
    }
}