How to save CPU cycles when searching for a value in a sorted list?

后端 未结 6 1428
不思量自难忘°
不思量自难忘° 2021-02-10 05:16

In CodinGame learning platform, one of the questions used as an example in a C# tutorial is this one:

The aim of this exercise is to check the presence of

6条回答
  •  無奈伤痛
    2021-02-10 05:34

     public static bool Exists(int[] ints, int k)
            {
                var d = 0;
                var f = ints.Length - 1;
                if (d > f) return false;
                if (k > ints[f] || k < ints[d]) return false;
                if (k == ints[f] || k == ints[d]) return true;
                return (BinarySearch(ints, k, d, f) > 0);
            }
    
     public static int BinarySearch(int[] V, int Key, int begin, int end)
            {
                if (begin > end)
                    return -1;
                var MidellIndex = (begin + end) / 2;
    
                if (Key == V[MidellIndex])
                    return MidellIndex;
                else
                {
                    if (Key > V[MidellIndex])
                    {
                        begin = MidellIndex + 1;
                        return BinarySearch(V, Key, begin, end);
                    }
                    else
                    {
                        end = MidellIndex - 1;
                        return BinarySearch(V, Key, begin, end);
                    }
                }
    
            }
    

提交回复
热议问题