Created
December 13, 2013 21:15
-
-
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
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
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