Skip to content

Instantly share code, notes, and snippets.

@Larry57
Created December 13, 2013 21:15
Show Gist options
  • Save Larry57/7951438 to your computer and use it in GitHub Desktop.
Save Larry57/7951438 to your computer and use it in GitHub Desktop.
This extension method performs a BinarySearch in a TeaFile file. http://discretelogics.com/teafiles
public static int BinarySearch<T, U>(this TeaFile<T> tf, U target, Func<T, U> indexer) where T : struct
{
var lo = 0;
var hi = (int)tf.Count - 1;
var comp = Comparer<U>.Default;
while(lo <= hi)
{
var median = lo + (hi - lo >> 1);
var num = comp.Compare(indexer(tf.Items[median]), target);
if (num == 0)
return median;
if (num < 0)
lo = median + 1;
else
hi = median - 1;
}
return ~lo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment