include iostream include cstdlib include ctime using namespace std int

 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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int BinSearch(const int* arr, int count, int key);
int main()
{
srand(time(NULL));
setlocale(0,"");
int n;
cout << "Input elements of array: ";
cin>>n;
int *arr = new int[n];
for(int i=0;i<n;i++)
arr[i]=rand()%10;
int key;
cout << "key: ";
cin >> key;
for(i=0;i<n;i++){
cout << arr[i] << endl;
}
if(BinSearch(arr, n, key) != -1)
cout << "Yes" << endl;
else cout << "No" << endl;
delete arr;
return 0;
}
int BinSearch(const int* arr, int count, int key)
{
int l = 0; // bottom
int u = count - 1; // top
while (l <= u) {
int m = (l + u) / 2;
if (arr[m] == key) return m;
if (arr[m] < key) l = m + 1;
if (arr[m] > key) u = m - 1;
}
return -1;
}