-
Notifications
You must be signed in to change notification settings - Fork 69
/
BinarySearch.cpp
44 lines (38 loc) · 1.04 KB
/
BinarySearch.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
#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;
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;
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);
}
else if ( tgt > arr[mid])
{
st = mid + 1;
}
else if ( tgt < arr[mid])
{
end = mid - 1;
}
}
cout << " Number is not found. " << endl;
return 0;
}