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

后端 未结 6 1409
不思量自难忘°
不思量自难忘° 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:52

    Here is a fast method for an ordered array

    public static class Answer
    {
        public static bool Exists( int[] ints, int k )
        {
            var lower = 0;
            var upper = ints.Length - 1;
    
            if ( k < ints[lower] || k > ints[upper] ) return false;
            if ( k == ints[lower] ) return true;
            if ( k == ints[upper] ) return true;
    
            do
            {
                var middle = lower + ( upper - lower ) / 2;
    
                if ( ints[middle] == k ) return true;
                if ( lower == upper ) return false;
    
                if ( k < ints[middle] )
                    upper = Math.Max( lower, middle - 1 );
                else
                    lower = Math.Min( upper, middle + 1 );
            } while ( true );
        }
    }
    

    Takes around 50 ticks on my cpu (with 90.000.000 items in the array)

    Sample on dotnetfiddle

提交回复
热议问题