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

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

    Yes, BinarySearch would be faster than most algorithms you can write manually. However, if the intent of the exercise is to learn how to write an algorithm, you are on the right track. Your algorithm, though, makes an unnecessary check with if (i > k) ... why do you need this?

    Below is my general algorithm for simple requirements like this. The while loop like this is slightly more performant than a for-loop and out performs a foreach easily.

    public class Answer
    {
        public static bool Exists(int[] ints, int k)
        {
            var i = 0;
            var hasValue = false;
    
            while(i < ints.Length && !hasValue)
            {
                hasValue = ints[i] == k;
                ++i;
            }
    
            return hasValue;
        }
    }
    

提交回复
热议问题