Skip to content

Instantly share code, notes, and snippets.

@ilearnio
Last active May 13, 2016 20:06
Show Gist options
  • Save ilearnio/728413614bbd49fecd705e8a926fc3d9 to your computer and use it in GitHub Desktop.
Save ilearnio/728413614bbd49fecd705e8a926fc3d9 to your computer and use it in GitHub Desktop.
Binary search realization in C (simplest and probably fastest)
#include <math.h>
#include <stdbool.h>
bool binarySearch(int value, int values[], int n)
{
// Memorize the offset of a half rather then create an array on each iteration
int offset = 0;
int divider = n;
while (divider > 0) {
divider = round((divider + 1) / 2); // round up
if (values[offset + divider] <= value) {
if (offset + divider < n) {
offset += divider;
}
}
if (values[offset] == value) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment