Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 337ce10

Browse files
Binary_Search_Iter_Recur.cpp
Contains both Iterative and Recursive method for Binary Search. This solves fnplus#65
1 parent 63b8d0c commit 337ce10

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <stdio.h>
2+
3+
//Recursive Method
4+
int binarySearchR(int arr[], int l, int r, int x)
5+
{
6+
if (r >= l) {
7+
int mid = l + (r - l) / 2;
8+
9+
if (arr[mid] == x)
10+
return mid;
11+
12+
if (arr[mid] > x)
13+
return binarySearchR(arr, l, mid - 1, x);
14+
15+
return binarySearchR(arr, mid + 1, r, x);
16+
}
17+
18+
return -1;
19+
}
20+
21+
//Iterative Method
22+
int binarySearchI(int arr[], int l, int r, int x)
23+
{
24+
while (l <= r) {
25+
int m = l + (r - l) / 2;
26+
27+
if (arr[m] == x)
28+
return m;
29+
30+
if (arr[m] < x)
31+
l = m + 1;
32+
33+
else
34+
r = m - 1;
35+
}
36+
37+
return -1;
38+
}
39+
40+
int main(void)
41+
{
42+
int n;
43+
printf("Size : ");
44+
scanf("%d",&n);
45+
46+
int arr[n];
47+
48+
for(int i=0;i<n;i++)
49+
scanf("%d",&arr[i]);
50+
51+
int op;
52+
printf("Enter choice : \n 1. Recursive Method \n 2. Iterative Method ");
53+
scanf("%d",&op);
54+
55+
int x;
56+
printf("Value to search : ");
57+
scanf("%d",&x);
58+
59+
int result;
60+
61+
if(op==1)
62+
result = binarySearchR(arr, 0, n - 1, x);
63+
else
64+
result = binarySearchI(arr, 0, n - 1, x);
65+
66+
(result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result);
67+
return 0;
68+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /