-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.cpp
More file actions
48 lines (45 loc) · 832 Bytes
/
binary.cpp
File metadata and controls
48 lines (45 loc) · 832 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
45
46
#include<iostream>
using namespace std;
int main(){
int key;
int n;
int list[20];
int binary_search(int[],int,int);
cout<<"enter your number"<<endl;
cin>>n;
for(int i=0;i<n;i++)
cin>>list[i];
for(int i=0;i<n;i++)
cout<<"["<<list[i]<<"]"<<" ";
cout<<endl;
cout<<"enter your key"<<endl;
cin>>key;
int result=binary_search(list,key,n);
if(result==-1)
cout<<"the item is not found\n";
else
cout<<"the item is found at index"<<result<< " " << "the value is ="<<list[result];
return 0;
}
int binary_search(int list[20],int key,int n){
int left=0;
int right=n-1;
int found=0;
int mid;
int index;
do{
mid=(left+right)/2;
if(key==list[mid])
found=1;
else
if(key<list[mid])
right=mid-1;
else
left=mid+1;
}while(found==0&&left<right);
if(found==0)
index=-1;
else
index=mid;
return index;
}