forked from CodXCrypt/Cpp-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
43 lines (36 loc) · 771 Bytes
/
BinarySearch.cpp
File metadata and controls
43 lines (36 loc) · 771 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
#include <iostream>
using namespace std;
template<class T>
int bSearch(T arr[],int l, int r,T ele)
{
int mid = (l+r)/2;
if(l<r)
{
if(arr[mid] > ele)
bSearch(arr,l,mid-1,ele);
else if(arr[mid] < ele)
bSearch(arr,mid+1,r,ele);
else
return mid;
}
}
int main()
{
int pos,n,key,i;
cout<<"Enter the size of the array : ";
cin>>n;
int arr[n];
cout<<"Enter the "<<n<<" elements : ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the element to be found : ";
cin>>key;
pos = bSearch(arr,0,n-1,key);
if(pos != -1)
cout<<"Element is present at "<<pos<<" position";
else
cout<<"Element is not present";
return 0;
}