Skip to content

Commit 79c2a9b

Browse files
shubhendra-20MadhavBahl
authored andcommitted
Create day29a_solved (#215)
* Create day29a_solved Binary Search Using Iteration * Rename day29a_solved to day29a_shubhendra-20
1 parent 19a8d01 commit 79c2a9b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

day29/CPP/day29a_shubhendra-20

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Author: Shubhendra Singh
3+
Github: shubhendra-20
4+
*/
5+
6+
#include <iostream>
7+
using namespace std;
8+
9+
int binarySearch(int arr[], int l, int r, int x)
10+
{
11+
while (l <= r) {
12+
int mid = l + (r - l) / 2;
13+
if (arr[mid] == x)
14+
return mid;
15+
16+
if (arr[mid] < x)
17+
l = mid + 1;
18+
else
19+
r = mid - 1;
20+
}
21+
22+
return -1;
23+
}
24+
int main()
25+
{
26+
int n,i,x;
27+
cin>>n;
28+
int a[n];
29+
for(i=0;i<n;i++)
30+
{
31+
cin>>a[i];
32+
}
33+
cin>>x;
34+
int k= binarySearch(a,0,n-1,x);
35+
if(k==-1)
36+
{
37+
cout<<"element not found";
38+
}
39+
else
40+
{
41+
cout<<"element found at index "<<k+1;
42+
}
43+
return 0;
44+
}

0 commit comments

Comments
 (0)