Skip to content

Instantly share code, notes, and snippets.

@techisbeautiful
Created July 12, 2022 08:02
Show Gist options
  • Save techisbeautiful/629a36e268c758cc5414d42d4b5281b8 to your computer and use it in GitHub Desktop.
Save techisbeautiful/629a36e268c758cc5414d42d4b5281b8 to your computer and use it in GitHub Desktop.
int binarySearch(int dataCollection[], int element) {
int left = 0, right = dataCollection.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Verify if element is present at mid
if (dataCollection[mid] == element)
return mid;
// If element greater, ignore left half
if (dataCollection[mid] < element)
left = mid + 1;
// If element is smaller, ignore right half
else
right = mid - 1;
}
// Element was not present
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment