-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search - Find the number
53 lines (44 loc) · 1.04 KB
/
Binary Search - Find the number
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
#include <iostream>
using namespace std;
int binarysearch(const int[], int, int);
const int size = 10;
int main()
{
int idin[size] = {12, 32, 32, 234, 12, 32, 14, 34, 12, 534};
int result, empID;
cout << "Enter an ID number to get where it is stored: ";
cin >> empID;
result = binarysearch(idin, size, empID);
if (result == -1)
{
cout << "The ID number does not exist in the array.\n";
}
else
{
cout << "The ID is found at element " << result + 1 << endl;
}
return 0;
}
int binarysearch(const int array[], int size, int value)
{
int first = 0, last = size - 1, middle, position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
{
last = middle - 1;
}
else
{
first = middle + 1;
}
}
return position;
}