Finding the closest data point in a sequential list Given a List&lt;double&gt; and a double, it will find the closest value and return the index of the closest value in the list. The list will always be in order.

private int FindClosestPoint(double val, List&lt;Double&gt; list)
{
    int ret = new int();

    int max = list.Count;
    int min = 0;
    int index = max / 2;

    while (max - min &gt; 1)
    {
        if (val &lt; list[index])
            max = index;
        else if (val &gt; list[index])
            min = index;
        else
            return index;

        index = (max - min) / 2 + min;
    }

    if (max != list.Count &amp;&amp; min != 0)
    {
        if (Math.Abs(list[max] - val) &lt; Math.Abs(list[min] - val))
            ret = max;
        else
            ret = min;
    }
    return ret;
}
Bug

Suppose list[0] = 0, list[1] = 1, and val = 2.  After doing the binary search, you are left with min = 1 and max = 2.

When we get here:


if (max != list.Count &amp;&amp; min != 0)



the block is skipped because max == list.Count.  This is correct because you don't want to deference list[max].  However, you end up returning ret which was never set and still contains 0.  The correct index to return would be 1.

I believe you can fix your function by eliminating the ret variable and returning min instead.  In other words:

private int FindClosestPoint(double val, List&lt;Double&gt; list)
{
    int max = list.Count;
    int min = 0;
    int index = max / 2;

    while (max - min &gt; 1)
    {
        if (val &lt; list[index])
            max = index;
        else if (val &gt; list[index])
            min = index;
        else
            return index;

        index = (max - min) / 2 + min;
    }

    if (max != list.Count &amp;&amp;
            Math.Abs(list[max] - val) &lt; Math.Abs(list[min] - val))
    {
        return max;
    }
    return min;
}


Strange way to initialize an int

Also I noticed this strange line:


int ret = new int();



I'm not sure why you didn't just initialize ret the same way as you did with min:

int ret = 0;


The two statements are equivalent but since int is a value type, the former statement is odd because it makes it look like you are trying to allocate an object.