-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17th_binarysearch.cpp
More file actions
44 lines (43 loc) · 879 Bytes
/
17th_binarysearch.cpp
File metadata and controls
44 lines (43 loc) · 879 Bytes
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
//implement binary search using loops
#include <bits/stdc++.h>
using namespace std;
int binary_search(int arr[],int n,int key)
{
int high=n-1;
int low=0;
int mid=(low+high)/2;
while(low<high)
{
if(arr[mid]==key)
return 1;
else if(arr[mid]<key)
{
low=mid+1;
}
else if(arr[mid]>key)
{
high=mid-1;
}
mid=(low+high)/2;
}
return 0;
}
int main()
{
int n;
cout<<"Enter number of elements in the array : ";
cin>>n;
cout<<"Enter elements in the array in a sorted manner : \n";
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int key;
cout<<"Enter key to search : ";
cin>>key;
if(binary_search(arr,n,key))
cout<<"Key : "<<key<<" is present.\n";
else
cout<<"Key : "<<key<<" is not present.\n";
}