Skip to content

Instantly share code, notes, and snippets.

@ivankahl
Last active November 19, 2015 20:03
Show Gist options
  • Save ivankahl/a3cb141c4a7c4606f72b to your computer and use it in GitHub Desktop.
Save ivankahl/a3cb141c4a7c4606f72b to your computer and use it in GitHub Desktop.
// Needs the array to already be SORTED!
static int BinarySearch(int[] items, int itemToSearch)
{
// Create a variable to store the lower boundary
int start = 0,
// Create a variable to store the upper boundary
end = items.Length - 1,
// Create a variable to store the middle of the boundary
mid = (start + end) / 2;
// Create a variable to determine whether the item is
// actually found
bool found = false;
// Carry on looping while the lower bound is smaller than
// the upper bound and the value is still not found
while (start <= end && !found)
{
// Check is the value is in the upper half of the array
if (items[mid] < itemToSearch)
{
// If it is, set the lower bound to the middle value
// + 1
start = mid + 1;
// Recalculate the mid value
mid = (start + end) / 2;
}
// Check if the value is in the lower half of the array
else if (itemToSearch < items[mid])
{
// If it is, set the upper bound to the middle value
// - 1
end = mid - 1;
// Recalculate the mid value
mid = (start + end) / 2;
}
// Check if the mid value matches our desired value
else if (items[mid] == itemToSearch)
{
// If it does, set the boolean to true so we can exit
// the loop
found = true;
}
}
// Check if the array exited because the start boundary became
// larger than the end boundary or whether the item was actually
// found
if (found)
// If the item was found, return its position
return mid;
else
// Else return -1 for NOT FOUND
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment