Skip to content

Instantly share code, notes, and snippets.

@ikbear
Created May 27, 2015 06:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikbear/3b15c218b5fa4ba014fc to your computer and use it in GitHub Desktop.
Save ikbear/3b15c218b5fa4ba014fc to your computer and use it in GitHub Desktop.
Binary Search in C
#include <stdio.h>
int binary_search(int *a, int length, int target)
{
int left = 0;
int right = length - 1;
int middle = 0;
while (left <= right)
{
middle = (left + right) >> 1;
if (a[middle] > target)
{
right = middle - 1;
}
else if (a[middle] < target)
{
left = middle + 1;
}
else
{
return middle;
}
}
return -1;
}
int main()
{
int a[5] = {2, 3, 4, 8, 10};
int i = binary_search(a, 5, 8);
printf("%d\n", i);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment