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
25 int mid = l + (r - l) / 2;
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
53 int mid = l + (r - l) / 2;
67 mid = l + (r - l) / 2;
◆ main()
Main function.
void test()
Test implementations.
Definition: binary_search.c:75
◆ test()
Test implementations.
78 int arr[] = {2, 3, 4, 10, 40};
80 int n =
sizeof(arr) /
sizeof(arr[0]);
82 printf(
"Test 1.... ");
88 printf(
"passed recursive... ");
91 printf(
"passed iterative...\n");
93 printf(
"Test 2.... ");
98 printf(
"passed recursive... ");
100 assert(result == -1);
101 printf(
"passed iterative...\n");
int binarysearch2(const int *arr, int l, int r, int x)
Iterative implementation.
Definition: binary_search.c:51