ceesort/src/bsrch.c

40 lines
885 B
C
Raw Normal View History

2022-05-26 13:34:12 +01:00
/*
* Filename: bsrch.c
* Author(s): Roland (r.weirhowell@gmail.com)
* Description: Perform binary search on an integer array
* License: MIT (https://spdx.org/licenses/MIT.html)
*/
2022-03-18 10:44:20 +00:00
#include "bsrch.h"
#include <stdbool.h>
2022-03-26 13:30:43 +00:00
#include <stddef.h>
2022-03-18 10:44:20 +00:00
int bsrch(int target, int* arr, size_t n)
{
2022-04-01 10:34:34 +01:00
// TODO: Find a way to error if list is out of order
2022-03-18 10:44:20 +00:00
bool found = false;
int start = 0, end = n - 1;
if (arr[start] > target || arr[end] < target) return -1;
2022-03-26 13:30:43 +00:00
int mid = (start + end) / 2;
2022-03-18 10:44:20 +00:00
while (!found)
{
if (arr[mid] == target) found = true;
if (start == end && !found) return -1;
else if (arr[mid] < target)
{
start = mid + 1;
2022-03-26 13:30:43 +00:00
mid = (start + end) / 2;
2022-03-18 10:44:20 +00:00
}
else if (arr[mid] > target)
{
end = mid - 1;
2022-03-26 13:30:43 +00:00
mid = (start + end) / 2;
2022-03-18 10:44:20 +00:00
}
}
return mid;
}