Skip to content

Instantly share code, notes, and snippets.

@blam23
Created November 23, 2016 20:41
Show Gist options
  • Save blam23/76988c32377296600c4ac881a4234971 to your computer and use it in GitHub Desktop.
Save blam23/76988c32377296600c4ac881a4234971 to your computer and use it in GitHub Desktop.
"Binary" Search for a double in C#. Uses difference from needle for midpoint as opposed to halving sum
private static int BinarySearch(List<double> haystack, double needle, double tolerance = 0.0000001)
{
var left = 0;
var right = haystack.Count - 1;
while (needle <= haystack[right] && needle > haystack[left])
{
var leftDiff = needle - haystack[left];
var rangeDiff = haystack[right] - haystack[left];
var count = right - left;
var range = (int)(leftDiff/rangeDiff*count + left);
if (needle > haystack[range])
{
left = range + 1;
}
else if (needle < haystack[range])
{
right = range - 1;
}
else
{
left = range;
}
}
if (Math.Abs(needle - haystack[left]) < tolerance)
{
return left;
}
return -1;
}
[TestMethod]
public void BinarySearchTest()
{
var test = new List<double>
{
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
};
for(var i = 0; i < test.Count; i++)
{
Assert.AreEqual(i, BinarySearch(test, i));
}
test = new List<double>
{
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
};
for (var i = 0; i < test.Count; i++)
{
Assert.AreEqual(i, BinarySearch(test, i));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment