From 3b0ff5fd7b86aefebb4ad164fe3479905b4d8349 Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Tue, 30 Jun 2020 14:02:10 -0400 Subject: [PATCH] fixed binary_search for lgtm errors + added tests --- searching/binary_search.c | 43 +++++++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/searching/binary_search.c b/searching/binary_search.c index 78a4cf88..5b3ef3a4 100644 --- a/searching/binary_search.c +++ b/searching/binary_search.c @@ -1,9 +1,21 @@ +/** + * @file + * @brief Program to perform [binary + * search](https://en.wikipedia.org/wiki/Binary_search_algorithm) of a target + * value in a given *sorted* array. + */ +#include #include -// Recursive Function- It returns location of x assumiung array arr[l..r] is -// present, otherwise -1 - -int binarysearch(int arr[], int l, int r, int x) +/** Recursive 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 binarysearch(const int *arr, int l, int r, int x) { if (r >= l) { @@ -25,18 +37,33 @@ int binarysearch(int arr[], int l, int r, int x) return -1; } -int main(void) +/** Test implementations */ +void test() { // give function an array to work with int arr[] = {2, 3, 4, 10, 40}; // get size of array int n = sizeof(arr) / sizeof(arr[0]); + + printf("Test 1.... "); // set value to look for int x = 10; // set result to what is returned from binarysearch int result = binarysearch(arr, 0, n - 1, x); - // print out result - (result == -1) ? printf("Element is not in the array\n") - : printf("Element is present at index %d\n", result); + assert(result == 3); + printf("passed\n"); + + printf("Test 2.... "); + x = 5; + // set result to what is returned from binarysearch + result = binarysearch(arr, 0, n - 1, x); + assert(result == -1); + printf("passed\n"); +} + +/** Main function */ +int main(void) +{ + test(); return 0; }