繁体   English   中英

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

[英]Interpolation Search, finding the closest value

我正在尝试使用插值搜索算法来找到一个值并将其返回。 (这是当前的操作)。 我正在尝试修改它,以便它返回一个数字,如果在数组中未找到要搜索的项目,则可以使用该数字查找与输入项目最接近的值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM