-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbinary.cpp
More file actions
42 lines (39 loc) · 874 Bytes
/
binary.cpp
File metadata and controls
42 lines (39 loc) · 874 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
#include <iostream>
using namespace std;
int main()
{
int count, i, arr[30], num, first, last, middle;
cout<<"How many elements would you like to enter?:";
cin>>count;
for (i=0; i<count; i++)
{
cout<<"Enter numbers in accending order "<<(i+1)<<": ";
cin>>arr[i];
}
cout<<"Enter the number that you want to search:";
cin>>num;
first = 0;
last = count-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < num)
{
first = middle + 1;
}
else if(arr[middle] == num)
{
cout<<num<<" Found in the array at the location "<<middle+1<<"\n";
break;
}
else {
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<num<<" Element is not found in the array";
}
return 0;
}