我有一个数组A{1,2,3,4,5,6,7,8,9},给定一个数B=3.789,如何从数组A中快速找出与B最接近的数字!关键找的要快!应为数组A中的数可能很多,一定要以最快的方式找出来!
如何计算?

解决方案 »

  1.   

    首先确定A是按大小顺序排列
    然后用对分查找,参考如下代码:
    private int BinarySearch(double[] array, double value)
    {
        if (array == null || array.Length <= 0) return -1;
        int low = 0;
        int hi = array.Length - 1;
        while (low <= hi)
        {
            int m = low + ((hi - low) >> 1); // 中间值
            if (value > array[m])
                low = m + 1;
            else hi = m - 1;
        }
        low = Math.Min(low, array.Length - 1);
        if (low <= 0) return low;
        else return value - array[low - 1] < array[low] - value ? low - 1 : low;
    }private void button1_Click(object sender)
    {
        double[] A = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        //Array.Sort(A);//初始化,之后可以顺序插入
        double[] B = { 1, 2, 2.5, 3.51, 3.49, 9, 100};
        for (int i = 0; i < B.Length; i++)
        {
            int j = BinarySearch(A, B[i]);
            Console.WriteLine("B={0},Index:{1},Value:{2}", B[i], j, j < 0 ? -1 : A[j]);
        }
    }---输出----
    B=1,Index:0,Value:1
    B=2,Index:1,Value:2
    B=2.5,Index:2,Value:3
    B=3.51,Index:3,Value:4
    B=3.49,Index:2,Value:3
    B=9,Index:8,Value:9
    B=100,Index:8,Value:9
      

  2.   

    有人说用linq写,这算写着玩,不能保证性能,以测试结果为主。
    double[] A = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    //Array.Sort(A);//初始化,之后可以顺序插入
    double[] B = { 1, 2, 2.5, 3.51, 3.49, 9, 100};
    for (int i = 0; i < B.Length; i++)
    {
        IEnumerable<double> query =
            from student in A
            orderby Math.Abs(student - B[i])
            select student;
        Console.WriteLine("B={0},Value:{1}", B[i], query.First<double>());
    }---输出---- 
    B=1,Value:1
    B=2,Value:2
    B=2.5,Value:2
    B=3.51,Value:4
    B=3.49,Value:3
    B=9,Value:9
    B=100,Value:9