mirror of https://github.com/TheAlgorithms/C
fixed binary_search for lgtm errors + added tests
This commit is contained in:
parent
cc45bea17d
commit
3b0ff5fd7b
|
@ -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 <assert.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue