forked from wie-chandigarhuniversity/HacktoberFest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinarysearch.cpp
44 lines (43 loc) · 896 Bytes
/
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>
using namespace std;
int main()
{
int N,i,low,mid,high,key;
cout << "Enter the length of array" << endl;
cin >> N;
int input_array[N];
cout << "Enter array elements in increasing order" << endl;
for(i=0;i<N;i++)
{
cin >> input_array[i];
}
cout << "Enter the element to be searched" << endl;
cin >> key;
low=0;
high=N-1;
while(low<=high)
{
mid=(low+high)/2;
if(key<input_array[mid])
{
high=mid-1; // if yes, sub-array ends at index mid-1
}
else if(key>input_array[mid])
{
low=mid+1;
}
else
{
break;
}
}
if(key==input_array[mid])
{
cout << "Key Found" << mid << endl;
}
else
{
cout << "key is not found" << endl;
}
return 0;
}