Skip to content

Instantly share code, notes, and snippets.

@asim
Created November 29, 2010 14:26
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 asim/720011 to your computer and use it in GitHub Desktop.
Save asim/720011 to your computer and use it in GitHub Desktop.
binary search in C without looking at the implementation
#include <stdio.h>
int bsearch(int left, int right, int find, int *a) {
if (left > right)
return -1;
int mid = (left + right) / 2;
if (find == a[mid])
return mid;
else if(find < a[mid])
return bsearch(left, (mid - 1), find, a);
else if(find > a[mid])
return bsearch((mid + 1), right, find, a);
}
int main() {
int a[] = { 0, 2, 4, 6, 8, 10, 12 };
int f = bsearch(0, 7, 10, a);
printf("position of %d is: %d\n", 10, f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment