Skip to content

Instantly share code, notes, and snippets.

@way2datta
Last active Jul 9, 2021
Embed
What would you like to do?
Human Readable Binary Search
public class IntArray
{
public static int BinarySearch(int[] items, int searchTerm)
{
return SearchRecursively(items, searchTerm, 0, items.Length - 1);
}
private static int SearchRecursively(int[] items, int searchTerm, int lowerIndex, int upperIndex)
{
var scannedAllItems = lowerIndex > upperIndex;
if (scannedAllItems) return -1;
var middleIndex = (lowerIndex + upperIndex) / 2;
var middleItem = items[middleIndex];
var isItemPresentAtMiddleIndex = items[middleIndex] == searchTerm;
if (isItemPresentAtMiddleIndex) return middleIndex;
var searchItemInLowerHalf = middleItem.CompareTo(searchTerm) > 0;
if (searchItemInLowerHalf) return SearchRecursively(items, searchTerm, lowerIndex, middleIndex - 1);
var searchItemInUpperHalf = middleItem.CompareTo(searchTerm) < 0;
if (searchItemInUpperHalf) return SearchRecursively(items, searchTerm, middleIndex + 1, upperIndex);
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment