2
2
/*
3
3
* Part of Cosmos by OpenGenus Foundation
4
4
*/
5
+ // A recursive binary search function. It returns
6
+ // location of x in given array arr[l..r] is present,
7
+ // otherwise -1
5
8
int recursiveBinarySearch (int arr [], int l , int r , int x )
6
9
{
7
10
if (r >= l )
8
11
{
9
12
int mid = l + (r - l )/2 ;
10
-
13
+ // If the element is present at the middle
14
+ // itself
11
15
if (arr [mid ] == x )
12
16
return mid ;
17
+ // If element is smaller than mid, then
18
+ // it can only be present in left subarray
13
19
if (arr [mid ] > x )
14
20
return recursiveBinarySearch (arr , l , mid - 1 , x );
15
-
21
+ // Else the element can only be present
22
+ // in right subarray
16
23
return recursiveBinarySearch (arr , mid + 1 , r , x );
17
24
}
25
+ // We reach here when element is not
26
+ // present in array
18
27
return -1 ;
19
28
}
20
-
29
+ // A iterative binary search function. It returns
30
+ // location of x in given array arr[l..r] is present,
31
+ // otherwise -1
21
32
int binarySearch (int arr [], int l , int r , int x )
22
33
{
23
34
while (l <= r )
24
35
{
25
36
int mid = l + (r - l )/2 ;
26
-
37
+ // If the element is present at the middle
38
+ // itself
27
39
if (arr [mid ] == x )
28
40
return mid ;
29
-
41
+ // If element is greater than mid, then
42
+ // it can only be present in right subarray
30
43
if (arr [mid ] < x )
31
44
l = mid + 1 ;
32
-
45
+ // Else the element can only be present
46
+ // in right subarray
33
47
else
34
48
r = mid - 1 ;
35
49
}
36
- return -1 ;
50
+ // We reach here when element is not
51
+ // present in array
52
+ return -1 ;
37
53
}
38
54
39
55
int main (void )
40
56
{
41
57
int arr [] = {1 , 2 , 3 , 5 };
42
58
int size = sizeof (arr )/ sizeof (arr [0 ]);
43
59
int find = 3 ;
60
+ //Printing the position of element using recursive binary search
44
61
printf ("Position of %d is %d\n" , find , recursiveBinarySearch (arr , 0 , size - 1 , find ));
62
+ //Printing the position of element using iterative binary search
45
63
printf ("Position of %d is %d\n" , find , binarySearch (arr , 0 , size - 1 , find ));
46
64
return 0 ;
47
- }
65
+ }
0 commit comments