插值搜索,查找最接近的值



我正在尝试使用插值搜索算法来查找值并返回它。(这就是它目前所做的(。我正在尝试修改它,以便它返回一个数字,如果在数组中找不到搜索的项目,我可以使用该数字来查找与输入项目最接近的值。

public static int InterSearch(double[] array, double data)
        {
            int size = array.Length;
            int lo = 0;
            int mid = -1;
            int hi = array.Length - 1;
            int index = -1;
            int count = 0;
            while (lo <= hi)
            {
                mid = (int)(lo + (((double)(hi - lo) / (array[hi] - array[lo])) * (data - array[lo])));
                count++;
                if (array[mid] == data)
                {
                    index = mid;
                    break;
                }
                else
                {
                    if (array[mid] < data)
                        lo = mid + 1;
                    else
                        hi = mid - 1;
                }
            }
            return index;
        }

您可以使用查找最接近值的聚合。这是一种自定义扩展方法,但您明白了。

 public static double GetValueClosestTo(this List<double> values, double closestTo)
 {
     return values.Aggregate((x, y) => Math.Abs(x - closestTo) < Math.Abs(y - closestTo) ? x : y);
 }

假设您有以下数组{1, 5, 9.2, 6, 17},并且您测试了以下数组{6, 15, 5.2}。您将使用以下代码

var sourceArray = new [] {1, 5, 9.2, 6, 17}.ToList() // for simplicity i use a list
var closestToX = sourceArray.GetValueClosestTo(6); // this return 6
closestToX = sourceArray.GetValueClosestTo(15); // this return 17
closestToX = sourceArray.GetValueClosestTo(5.2); // this return 5

最新更新