Skip to content

Instantly share code, notes, and snippets.

@bor0
Created August 31, 2015 20:44
Show Gist options
  • Select an option

  • Save bor0/7cb63f3428e6329340c5 to your computer and use it in GitHub Desktop.

Select an option

Save bor0/7cb63f3428e6329340c5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define INTSIZE(x) (sizeof(x)/sizeof(int))
int bs_test[] = { 1, 5, 9, 11, 15, 19, 21, 22, 27, 31, 55, 59 };
int itera = 0;
int find_bs(int n) {
int low = 0, high = INTSIZE(bs_test) - 1, mid = 0;
while (low < high && mid != 1) {
mid = (low+high)/2;
itera++;
if (bs_test[mid] > n) high = mid + 1;
else if (bs_test[mid] < n) low = mid;
else return mid;
}
return -1;
}
int main() {
int x = find_bs(5);
printf("%d (%d)\n", x, itera);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment