Skip to content

Commit 4e51910

Browse files
Merge pull request #5 from pkdism/add_algos1
Add Binary Search
2 parents 3b1937f + 9a84ac4 commit 4e51910

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Binary Search.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <iostream>
2+
using namespace std;
3+
int binary_search(int a[],int l,int r,int key){
4+
while(l<=r){
5+
int m = l+(r-l)/2;
6+
if(key==a[m])
7+
return m;
8+
else if(key<a[m])
9+
r = m-1;
10+
else
11+
l = m+1;
12+
}
13+
return -1;
14+
}
15+
int main(int argc, char const *argv[])
16+
{
17+
int n,key;
18+
cout<<"Enter size of array: ";
19+
cin>>n;
20+
cout<<"Enter array elements: ";
21+
int a[n];
22+
for (int i = 0; i < n; ++i)
23+
{
24+
cin>>a[i];
25+
}
26+
cout<<"Enter search key: ";
27+
cin>>key;
28+
int res = binary_search(a,0,n-1,key);
29+
if(res != -1)
30+
cout<<key<<" found at index "<<res<<endl;
31+
else
32+
cout<<key<<" not found"<<endl;
33+
return 0;
34+
}

0 commit comments

Comments
 (0)