简体   繁体   English

二进制搜索最近值c#

[英]Binary Search Closest Value c#

i am using this binary search algorithm to find items in my array. 我正在使用这种二进制搜索算法来查找我的数组中的项目。 I am trying to make it so when i search for a value which doesn't appear in the array my program tells me, and it also reveals where the closest items are 我试图做到这一点,所以当我搜索程序中告诉我的数组中未出现的值时,它还会显示最近的项目在哪里

Example Array: (4, 6, 7, 8, 9) Search for 5 Result 6, 7. 示例数组:(4,6,7,8,9)搜索5结果6、7。

Every time i search for something which isn't an element within my array it returns 0, or -1. 每次我搜索数组中不是元素的东西时,它都会返回0或-1。 Can someone help me out, thanks? 有人可以帮我吗,谢谢?

  public static double BinarySearch(double[] a, double item)
    {
        int first = 0;
        int last = a.Length - 1;
        do
        {
            int mid = first + (last - first) / 2;
            if (item > a[mid])
                first = mid + 1;
            else
                last = mid - 1;
            if (a[mid] == item)
                return mid;
        } while (first <= last);       
        return -1;
    }

Suppose you would declare "mid" outside the loop and return it ? 假设您将在循环外部声明“ mid”并返回它? Instead of -1 ? 代替-1?

When your array is sorted and the searched value is not found, you will get a mid result pointing to the lower value in the array closest to your search value. 当对数组进行排序并且未找到搜索值时,您将获得中间结果,该结果指向数组中与您的搜索值最接近的较低值。 The element above your search value is contained in a[mid+1]. 搜索值上方的元素包含在a [mid + 1]中。 Small change: 小变化:

public static double BinarySearch(double[] a, double item)
{
    int first = 0;
    int last = a.Length - 1;
    int mid = 0;
    do
    {
        mid = first + (last - first) / 2;
        if (item > a[mid])
            first = mid + 1;
        else
            last = mid - 1;
        if (a[mid] == item)
            return mid;
    } while (first <= last);
    return mid;
}

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

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