-
-
Save anonymous/a0e79374e9235ecf985241bb47ae58b3 to your computer and use it in GitHub Desktop.
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
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