How do I find the closest array element to an arbitrary (non-member) number?

前端 未结 5 1467
闹比i
闹比i 2021-01-18 13:48

Seemingly similar questions: \"Finding closest number in an array\" (in Java) and \"find nearest match to array of doubles\" (actually a geography problem).

5条回答
  •  旧巷少年郎
    2021-01-18 14:54

    Perhaps not the fastest solution, but certainly pleasant eye-candy:

    double search;
    double[] array;
    
    var nearest = (
        from value in array
        orderby Math.Abs(value - search)
        select value).First();
    
    var index = array.IndexOf(nearest);
    

    Note that this will absolutely be slower than a binary search algorithm, because it need to process each element in the array and sorting means building a hash table of those items.

提交回复
热议问题