Skip to content

Instantly share code, notes, and snippets.

@deeja
Created June 13, 2019 09:58
Show Gist options
  • Save deeja/bd5b4273e6c980dee429a5bfa3782db4 to your computer and use it in GitHub Desktop.
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
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;
}
}
@deeja
Copy link
Author

deeja commented Jun 13, 2019

Array calls should max out around 15 accesses, even on the largest arrays

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment