Last active
May 13, 2016 20:06
-
-
Save ilearnio/728413614bbd49fecd705e8a926fc3d9 to your computer and use it in GitHub Desktop.
Binary search realization in C (simplest and probably fastest)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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