Finding the floor value in an array Problem:


  Given an sorted array of N distinct integers, find floor value of input 'key'. Say, A = {1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome.


How can I optimize my solution?

     private static int CalclualteFloorValue(int[] _sortedarray, int l, int r, int key)
        {
            if (_sortedarray[l] == key)
                return -1;




            int m = -1;

            while (l&lt;=r)
            {
                 m = (r+l)/ 2;

                if (_sortedarray[m] == key)
                {
                    return  _sortedarray[m - 1];

                }
                else if (_sortedarray[m] &lt; key)
                {
                    l = m+1;
                }
                else
                {
                    r = m-1;
                }
            }


            return _sortedarray[m];

        }

  int _floorValue = CalclualteFloorValue(_sortedarray, 0, _sortedarray.Length - 1,7);
In terms of speed, your solution is about as optimized as it can get.  In terms of readability, your solution has much room for improvement.  I prefer readability over speed.  You should try to make your code as readable as possible, then, if you have performance issues, search for bottlenecks using a profiler and optimize them.  The method body of CalclualteFloorValue can be made into a one-liner, which happens to be slower but is much more readable.

private static int CalclualteFloorValue(int[] sortedArray, int key)
{
    return sortedArray.Last(x =&gt; x &lt; key);
}


If you wish to keep the speed of your original solution and increase readability, there are many improvements you can make:


Have a consistent parameter naming convention.  _sortedarray has an underscore, but the other parameter names don't.  I prefer to only use underscores for variables declared within classes but not within methods.
_sortedarray should be lowerCamelCase.  That is, sortedArray.
If l will always be zero and r will always be array length - 1, declare them in the method body.  Don't make the method caller do unnecessary work.
Use descriptive variable names instead of single letters.


The beginning of the method will now look like this:

private static int CalclualteFloorValue(int[] sortedArray, int key)
{
    int left = 0;
    int right = sortedArray.Length - 1;