patterncsharpMinor
Finding the floor value in an array
Viewed 0 times
thearrayvaluefindingfloor
Problem
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?
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);Solution
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
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.
-
-
If
-
Use descriptive variable names instead of single letters.
The beginning of the method will now look like this:
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 => x < 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;Code Snippets
private static int CalclualteFloorValue(int[] sortedArray, int key)
{
return sortedArray.Last(x => x < key);
}private static int CalclualteFloorValue(int[] sortedArray, int key)
{
int left = 0;
int right = sortedArray.Length - 1;Context
StackExchange Code Review Q#105039, answer score: 2
Revisions (0)
No revisions yet.