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<=r)
{
m = (r+l)/ 2;
if (_sortedarray[m] == key)
{
return _sortedarray[m - 1];
}
else if (_sortedarray[m] < key)
{
l = m+1;
}
else
{
r = m-1;
}
}
return _sortedarray[m];
}
int _floorValue = CalclualteFloorValue(_sortedarray, 0, _sortedarray.Length - 1,7);
Array.BinarySearch<T>
method? Or you need to reimplement it yourself? – Dmitry yesterday