Created
June 13, 2019 09:58
-
-
Save deeja/bd5b4273e6c980dee429a5bfa3782db4 to your computer and use it in GitHub Desktop.
A Binary Search for the count of items that are less than a specified value
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
using System; | |
public class FindLessThanInOrderedList | |
{ | |
public int ArrayCalls { get; private set; } | |
public int FindLessThanBinarySearch(int[] numbers, int lessThan, int startIndex = 0, int endIndex = -1) | |
{ | |
if (endIndex == -1) endIndex = numbers.Length - 1; | |
if (endIndex - startIndex < 2) | |
{ | |
return SmallArrayCheck(numbers, lessThan, startIndex, endIndex); | |
} | |
int midPointIndex = (endIndex - startIndex) / 2 + startIndex; | |
var midPoint = numbers[midPointIndex]; | |
ArrayCalls++; | |
if (midPoint >= lessThan) | |
return FindLessThanBinarySearch(numbers, lessThan, startIndex, midPointIndex - 1); | |
return FindLessThanBinarySearch(numbers, lessThan, midPointIndex, endIndex); | |
} | |
private int SmallArrayCheck(int[] numbers, int lessThan, int startIndex, int endIndex) | |
{ | |
ArrayCalls++; | |
var endValue = numbers[endIndex]; | |
if (endValue < lessThan) | |
{ | |
return endIndex + 1; | |
} | |
ArrayCalls++; | |
var startValue = numbers[startIndex]; | |
if (startValue < lessThan) | |
{ | |
return startIndex + 1; | |
} | |
return startIndex; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Array calls should max out around 15 accesses, even on the largest arrays