Skip to content

Commit

Permalink
added iterative algorithm for binary_search
Browse files Browse the repository at this point in the history
  • Loading branch information
kvedala committed Jun 30, 2020
1 parent 3b0ff5f commit e75dfb8
Showing 1 changed file with 47 additions and 7 deletions.
54 changes: 47 additions & 7 deletions searching/binary_search.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
* @brief Program to perform [binary
* search](https://en.wikipedia.org/wiki/Binary_search_algorithm) of a target
* value in a given *sorted* array.
* @authors [James McDermott](https://github.com/theycallmemac) - recursive
* algorithm
* @authors [Krishna Vedala](https://github.com/kvedala) - iterative algorithm
*/
#include <assert.h>
#include <stdio.h>
Expand All @@ -15,7 +18,7 @@
* \returns location of x assuming array arr[l..r] is present
* \returns -1 otherwise
*/
int binarysearch(const int *arr, int l, int r, int x)
int binarysearch1(const int *arr, int l, int r, int x)
{
if (r >= l)
{
Expand All @@ -27,16 +30,47 @@ int binarysearch(const int *arr, int l, int r, int x)

// If element is smaller than middle
if (arr[mid] > x)
return binarysearch(arr, l, mid - 1, x);
return binarysearch1(arr, l, mid - 1, x);

// Else element is in right subarray
return binarysearch(arr, mid + 1, r, x);
return binarysearch1(arr, mid + 1, r, x);
}

// When element is not present in array
return -1;
}

/** Iterative implementation
* \param[in] arr array to search
* \param l left index of search range
* \param r right index of search range
* \param x target value to search for
* \returns location of x assuming array arr[l..r] is present
* \returns -1 otherwise
*/
int binarysearch2(const int *arr, int l, int r, int x)
{
int mid = l + (r - l) / 2;

while (arr[mid] != x)
{
if (r <= l || r < 0)
return -1;

if (arr[mid] > x)
// If element is smaller than middle
r = mid - 1;
else
// Else element is in right subarray
l = mid + 1;

mid = l + (r - l) / 2;
}

// When element is not present in array
return mid;
}

/** Test implementations */
void test()
{
Expand All @@ -49,16 +83,22 @@ void test()
// set value to look for
int x = 10;
// set result to what is returned from binarysearch
int result = binarysearch(arr, 0, n - 1, x);
int result = binarysearch1(arr, 0, n - 1, x);
assert(result == 3);
printf("passed\n");
printf("passed recursive... ");
result = binarysearch2(arr, 0, n - 1, x);
assert(result == 3);
printf("passed iterative...\n");

printf("Test 2.... ");
x = 5;
// set result to what is returned from binarysearch
result = binarysearch(arr, 0, n - 1, x);
result = binarysearch1(arr, 0, n - 1, x);
assert(result == -1);
printf("passed recursive... ");
result = binarysearch2(arr, 0, n - 1, x);
assert(result == -1);
printf("passed\n");
printf("passed iterative...\n");
}

/** Main function */
Expand Down

0 comments on commit e75dfb8

Please sign in to comment.