Skip to content

Commit eed9450

Browse files
authored
Add files via upload
1 parent 03b2909 commit eed9450

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

binery search iterative method.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
5+
int array[15], i, x, n;
6+
7+
int BinarySearch(int low, int high)
8+
{
9+
while(low<=high)
10+
{
11+
12+
13+
14+
int mid=(low+high)/2;
15+
16+
if (array[mid]==x)
17+
{
18+
return mid;
19+
}
20+
else if (array[mid] >x)
21+
{
22+
high=mid-1;
23+
}
24+
else
25+
{
26+
low=mid+1;
27+
}
28+
return -1;
29+
}
30+
}
31+
32+
33+
int main() {
34+
cout << "Input the size of array: ";
35+
cin >> n;
36+
37+
cout << "Input the values of the array (in sorted order): ";
38+
for (i = 0; i < n; i++) {
39+
cin >> array[i];
40+
}
41+
42+
cout << "Input the value you want to search: ";
43+
cin >> x;
44+
45+
// Call the function
46+
int result = BinarySearch(0, n - 1);
47+
if (result == -1) {
48+
cout << "The value is not found in the array.";
49+
} else {
50+
cout << "The value is found at index: " << result;
51+
}
52+
53+
return 0;
54+
}

0 commit comments

Comments
 (0)