Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Created November 27, 2023 01:29
Show Gist options
  • Save PeterWaIIace/af869f7bc2d7050004507fcd2aead4be to your computer and use it in GitHub Desktop.
Save PeterWaIIace/af869f7bc2d7050004507fcd2aead4be to your computer and use it in GitHub Desktop.
binary search in C
int32_t binary_search(const uint8_t * array, const uint32_t length, uint8_t val)
{
uint8_t low = 0;
uint8_t high = length;
do
{
uint8_t index = floor((low + high)/2);
if(val == array[index])
{
return index;
}
/* check if val is less than then value under the index*/
else if(val < array[index])
{
high = index;
}
else
{
low = index + 1;
}
}while(low < high);
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment