Program to perform binary search of a target value in a given sorted array.
More...
#include <assert.h>
#include <stdio.h>
Program to perform binary search of a target value in a given sorted array.
- Authors
- James McDermott - recursive algorithm
-
Krishna Vedala - iterative algorithm
◆ binarysearch1()
int binarysearch1 |
( |
const int * |
arr, |
|
|
int |
l, |
|
|
int |
r, |
|
|
int |
x |
|
) |
| |
Recursive implementation.
- Parameters
-
[in] | arr | array to search |
| l | left index of search range |
| r | right index of search range |
| x | target value to search for |
- Returns
- location of x assuming array arr[l..r] is present
-
-1 otherwise
22{
23 if (r >= l)
24 {
25 int mid = l + (r - l) / 2;
26
27
28 if (arr[mid] == x)
29 return mid;
30
31
32 if (arr[mid] > x)
34
35
37 }
38
39
40 return -1;
41}
int binarysearch1(const int *arr, int l, int r, int x)
Recursive implementation.
Definition: binary_search.c:21
◆ binarysearch2()
int binarysearch2 |
( |
const int * |
arr, |
|
|
int |
l, |
|
|
int |
r, |
|
|
int |
x |
|
) |
| |
Iterative implementation.
- Parameters
-
[in] | arr | array to search |
| l | left index of search range |
| r | right index of search range |
| x | target value to search for |
- Returns
- location of x assuming array arr[l..r] is present
-
-1 otherwise
52{
53 int mid = l + (r - l) / 2;
54
55 while (arr[mid] != x)
56 {
57 if (r <= l || r < 0)
58 return -1;
59
60 if (arr[mid] > x)
61
62 r = mid - 1;
63 else
64
65 l = mid + 1;
66
67 mid = l + (r - l) / 2;
68 }
69
70
71 return mid;
72}
◆ main()
Main function.
106{
108 return 0;
109}
void test()
Test implementations.
Definition: binary_search.c:75
◆ test()
Test implementations.
76{
77
78 int arr[] = {2, 3, 4, 10, 40};
79
80 int n = sizeof(arr) / sizeof(arr[0]);
81
82 printf("Test 1.... ");
83
84 int x = 10;
85
87 assert(result == 3);
88 printf("passed recursive... ");
90 assert(result == 3);
91 printf("passed iterative...\n");
92
93 printf("Test 2.... ");
94 x = 5;
95
97 assert(result == -1);
98 printf("passed recursive... ");
100 assert(result == -1);
101 printf("passed iterative...\n");
102}
int binarysearch2(const int *arr, int l, int r, int x)
Iterative implementation.
Definition: binary_search.c:51