Skip to content

Instantly share code, notes, and snippets.

/binsearch Secret

Created February 4, 2017 01:47
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 anonymous/a0e79374e9235ecf985241bb47ae58b3 to your computer and use it in GitHub Desktop.
Save anonymous/a0e79374e9235ecf985241bb47ae58b3 to your computer and use it in GitHub Desktop.
int BinarySearch (int* array, int key, int arraylenght) //id probably pass this function the max too
{ //Note that this only works for sorted arrays,
//so you need to input your values in rising order,
//hopefully not a problem.
int start = 0;
int end = max - 1;
int mid;
int prev=-1; //This is our addition to the binary search, -1 is assumed to be an invalid value
while (true) //don't do this when you program a car break-system
{
mid = (start + end) / 2;
if (key == a[mid]) //we found the exact value we wanted, return
return mid;
if (prev==mid) //we found that this is the same value we compared to last time, return
{
return mid;
}
else if (key < a[mid])
{
end = mid - 1;
}
else
{
start = mid + 1;
}
prev=mid;
}
return -1; //The compiler wants to be sure we always return values, so we need to put this here, this will never execute
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment