forked from MohitR1999/cpp-store
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.cpp
More file actions
44 lines (35 loc) · 753 Bytes
/
binarySearch.cpp
File metadata and controls
44 lines (35 loc) · 753 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
#include "iostream"
#include "algorithm"
using namespace std;
int binarySearch(int arr[], int n, int val)
{
int s=0 ,e = n-1;
while(s<=e)
{
int mid = s + (e-s)/ 2;
if(arr[mid]==val)
return mid;
else if(arr[mid]<val)
s=mid+1;
else if(arr[mid>val])
e = mid-1;
}
return -1;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0 ;i<n ;i++)
cin>>arr[i];
sort(arr, arr+n);
int val;
cout<<"enter value to be searched in the array"<<endl;
cin>>val;
int res = binarySearch(arr,n,val);
if(res== -1)
cout<<"element is not present in the array"<<endl;
else
cout<<"element is present in array"<<endl;
}