Skip to content

Commit fa1510f

Browse files
Binary Search
1 parent d47dee4 commit fa1510f

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Diff for: BinarySearch.cpp

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
#include <iostream>
3+
using namespace std;
4+
5+
template<class T>
6+
int bSearch(T arr[],int l, int r,T ele)
7+
{
8+
int mid = (l+r)/2;
9+
if(l<r)
10+
{
11+
if(arr[mid] > ele)
12+
bSearch(arr,l,mid-1,ele);
13+
else if(arr[mid] < ele)
14+
bSearch(arr,mid+1,r,ele);
15+
else
16+
return mid;
17+
}
18+
19+
}
20+
21+
int main()
22+
{
23+
int pos,n,key,i;
24+
cout<<"Enter the size of the array : ";
25+
cin>>n;
26+
int arr[n];
27+
cout<<"Enter the "<<n<<" elements : ";
28+
for(i=0;i<n;i++)
29+
{
30+
cin>>arr[i];
31+
}
32+
cout<<"Enter the element to be found : ";
33+
cin>>key;
34+
pos = bSearch(arr,0,n-1,key);
35+
if(pos != -1)
36+
cout<<"Element is present at "<<pos<<" position";
37+
else
38+
cout<<"Element is not present";
39+
40+
return 0;
41+
}
42+
43+

0 commit comments

Comments
 (0)