-
Notifications
You must be signed in to change notification settings - Fork 15
/
Binary search in c++
47 lines (38 loc) · 1.2 KB
/
Binary search in c++
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>
#include <conio.h>
using namespace std;
int main ()
{
int arr[100], st, mid, end, i, num, tgt;
cout << " Define the size of the array: " << endl;
cin >> num; // get size
cout << " Enter the values in sorted array either ascending or descending order: " << endl;
for (i = 0; i < num; i++)
{
cout << " arr [" << i << "] = ";
cin >> arr[i];
}
st = 0;
end = num - 1; // size of array (num) - 1
cout << " Define a value to be searched from sorted array: " << endl;
cin >> tgt;
while ( st <= end)
{
mid = ( st + end ) / 2;
if (arr[mid] == tgt)
{
cout << " Element is found at index " << (mid + 1);
exit (0); // use for exit program the program
}
else if ( tgt > arr[mid])
{
st = mid + 1; // set the new value for st variable
}
else if ( tgt < arr[mid])
{
end = mid - 1; // set the new value for end variable
}
}
cout << " Number is not found. " << endl;
return 0;
}