ceesort/src/bsrch.c

40 lines
874 B
C
Raw Permalink 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, int n)
2022-03-18 10:44:20 +00:00
{
2022-04-01 10:34:34 +01:00
// TODO: Find a way to error if list is out of order
int start = 0, end = n - 1;
2022-03-18 10:44:20 +00:00
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 (true)
2022-03-18 10:44:20 +00:00
{
if (arr[mid] == target) break;
if (start == end) return -1;
if (mid == end) return -1;
2022-03-18 10:44:20 +00:00
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;
}