mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
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>
|
#include <stdio.h>
|
||||||
|
|
||||||
// Recursive Function- It returns location of x assumiung array arr[l..r] is
|
/** Recursive implementation
|
||||||
// present, otherwise -1
|
* \param[in] arr array to search
|
||||||
|
* \param l left index of search range
|
||||||
int binarysearch(int arr[], int l, int r, int x)
|
* \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)
|
if (r >= l)
|
||||||
{
|
{
|
||||||
@ -25,18 +37,33 @@ int binarysearch(int arr[], int l, int r, int x)
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
int main(void)
|
/** Test implementations */
|
||||||
|
void test()
|
||||||
{
|
{
|
||||||
// give function an array to work with
|
// give function an array to work with
|
||||||
int arr[] = {2, 3, 4, 10, 40};
|
int arr[] = {2, 3, 4, 10, 40};
|
||||||
// get size of array
|
// get size of array
|
||||||
int n = sizeof(arr) / sizeof(arr[0]);
|
int n = sizeof(arr) / sizeof(arr[0]);
|
||||||
|
|
||||||
|
printf("Test 1.... ");
|
||||||
// set value to look for
|
// set value to look for
|
||||||
int x = 10;
|
int x = 10;
|
||||||
// set result to what is returned from binarysearch
|
// set result to what is returned from binarysearch
|
||||||
int result = binarysearch(arr, 0, n - 1, x);
|
int result = binarysearch(arr, 0, n - 1, x);
|
||||||
// print out result
|
assert(result == 3);
|
||||||
(result == -1) ? printf("Element is not in the array\n")
|
printf("passed\n");
|
||||||
: printf("Element is present at index %d\n", result);
|
|
||||||
|
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;
|
return 0;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user