Website Summary Files Commits Branches @commit @diff @stats
path: root / Sem. 06 / binarySearch.cpp
blob: c4132c98023d846c898e49cb272b68fe7771fb37 (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
#include <iostream>
using namespace std;

bool binarySearch(const int arr[], unsigned size, int searched)
{
	unsigned fromIndex = 0;
	unsigned toIndex = size - 1;

	while (fromIndex <= toIndex)
	{
		unsigned midIndex = fromIndex + (toIndex - fromIndex) / 2;

		if (arr[midIndex] == searched)
			return true;

		if (arr[midIndex] < searched)
			fromIndex = midIndex + 1;
		else
			toIndex = midIndex - 1;
	}

	return false;
}


int main()
{

	int arr[]  { 1, 2, 3, 4,5,6,7,8};
	cout << binarySearch(arr, 8);

}