-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary-search.cpp
51 lines (39 loc) · 1020 Bytes
/
Binary-search.cpp
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
45
46
47
48
49
50
51
# include<iostream>
using namespace std;
int BinarySearch(int arr[], int size, int key){
int s = 0;
int e = size-1;
int mid = (s+e)/2;
while(s<=e){
if(arr[mid]==key){
return mid;
}
else if(key>arr[mid]){
s = mid+1;
}
else{
e = mid-1;
}
mid = (s+e)/2;
}
return -1;
}
int main(){
int size;
cout<<"Enter the size of the array : "<<endl;
cin>>size;
int arr[size], i, key;
cout<<"Enter the array elements : "<<endl;
for(i=0; i<size; i++){
cin>>arr[i];
}
cout<<"Enter the key you want to search : "<<endl;
cin>>key;
if(BinarySearch(arr, size, key)==-1){
cout<<"No match found! "<<endl;
}
else{
cout<<"The index of "<< " "<< key<<" "<<"is = "<<BinarySearch(arr, size, key);
}
return 0;
}