Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
binary_search.c File Reference

Program to perform binary search of a target value in a given sorted array. More...

#include <assert.h>
#include <stdio.h>
Include dependency graph for binary_search.c:

Functions

int binarysearch1 (const int *arr, int l, int r, int x)
 Recursive implementation. More...
 
int binarysearch2 (const int *arr, int l, int r, int x)
 Iterative implementation. More...
 
void test ()
 Test implementations.
 
int main (void)
 Main function.
 

Detailed Description

Program to perform binary search of a target value in a given sorted array.

Authors
James McDermott - recursive algorithm
Krishna Vedala - iterative algorithm

Function Documentation

◆ binarysearch1()

int binarysearch1 ( const int *  arr,
int  l,
int  r,
int  x 
)

Recursive implementation.

Parameters
[in]arrarray to search
lleft index of search range
rright index of search range
xtarget 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  // If element is present at middle
28  if (arr[mid] == x)
29  return mid;
30 
31  // If element is smaller than middle
32  if (arr[mid] > x)
33  return binarysearch1(arr, l, mid - 1, x);
34 
35  // Else element is in right subarray
36  return binarysearch1(arr, mid + 1, r, x);
37  }
38 
39  // When element is not present in array
40  return -1;
41 }

◆ binarysearch2()

int binarysearch2 ( const int *  arr,
int  l,
int  r,
int  x 
)

Iterative implementation.

Parameters
[in]arrarray to search
lleft index of search range
rright index of search range
xtarget 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  // If element is smaller than middle
62  r = mid - 1;
63  else
64  // Else element is in right subarray
65  l = mid + 1;
66 
67  mid = l + (r - l) / 2;
68  }
69 
70  // When element is not present in array
71  return mid;
72 }
binarysearch1
int binarysearch1(const int *arr, int l, int r, int x)
Recursive implementation.
Definition: binary_search.c:21