Skip to content

Instantly share code, notes, and snippets.

@SanjeevMohindra
Last active January 3, 2017 04:47
Show Gist options
  • Save SanjeevMohindra/9f8cdb16650d2f1895c0eeadf6bb796b to your computer and use it in GitHub Desktop.
Save SanjeevMohindra/9f8cdb16650d2f1895c0eeadf6bb796b to your computer and use it in GitHub Desktop.
public static int binarySearch(final int[] inputSortedData, final int searchElement) {
int minLeft = 0;
int maxRight = inputSortedData.length - 1;
while ( minLeft <= maxRight ) {
final int middleElement = (minLeft + maxRight) / 2;
if (searchElement == inputSortedData[middleElement]) { return middleElement + 1; }
if (searchElement < inputSortedData[middleElement]) { maxRight = middleElement - 1; }
if (searchElement > inputSortedData[middleElement]) { minLeft = middleElement + 1; }
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment