-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
51 lines (51 loc) · 1.15 KB
/
binary_search.cpp
File metadata and controls
51 lines (51 loc) · 1.15 KB
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;
bool binarySearch(int list[] , int last ,int target ,int& locn){
int begin =0;
int end =last;
int mid;
bool found;
while (begin<=end)
{
mid =(begin +end)/2;
if(target>list[mid]){
begin = mid+1;
}
else if(target< list[mid]){
end = mid-1;
}
else{
break;
}
}
locn = mid;
if(target == list[mid]){
found = true;
}
else{
found = false;
}
return found;
}
int main(){
int n,t,locn;
int arr[10];
bool f;
cout<<"enter no.of elements: ";
cin>>n;
cout<<"enter array elements: "<<endl;
for (int i = 0; i < n; i++)
{
cin>>arr[i];
}
cout<<"Enter the number to be searched: ";
cin>>t;
f= binarySearch(arr,n-1,t ,locn);
if(f){
cout<<"Element "<<t<<" found in the list at position "<<locn+1<<endl;
}
else{
cout<<"Element "<<t<<" not found in the list"<<endl;
}
return 0;
}