Skip to content

Commit 622e9c6

Browse files
authored
A c++ program for binary search
1 parent 631fb5d commit 622e9c6

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Binary_Search_Program

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
int main()
5+
{
6+
int count, i, arr[30], num, first, last, middle;
7+
cout<<"how many elements would you like to enter?:";
8+
cin>>count;
9+
10+
for (i=0; i<count; i++)
11+
{
12+
cout<<"Enter number "<<(i+1)<<": ";
13+
cin>>arr[i];
14+
}
15+
cout<<"Enter the number that you want to search:";
16+
cin>>num;
17+
first = 0;
18+
last = count-1;
19+
middle = (first+last)/2;
20+
while (first <= last)
21+
{
22+
if(arr[middle] < num)
23+
{
24+
first = middle + 1;
25+
26+
}
27+
else if(arr[middle] == num)
28+
{
29+
cout<<num<<" found in the array at the location "<<middle+1<<"\n";
30+
break;
31+
}
32+
else {
33+
last = middle - 1;
34+
}
35+
middle = (first + last)/2;
36+
}
37+
if(first > last)
38+
{
39+
cout<<num<<" not found in the array";
40+
}
41+
return 0;
42+
}

0 commit comments

Comments
 (0)