The short answer is yes, up to 25%
We all know that in the .Net Framework, the BinarySearch is fast to search in List<>, but can we make it even faster?
The Question
We have a List with 1.000.000 numbers.
We create a function to see if a number exists in the collection
public bool ExistBinarySearch()
{
return _numbers.BinarySearch(numberToSearch) >= 0;
}
The Faster Binary Search is
public bool ExistFasterBinarySearch()
{
int low = 0;
int high = _numbers.Count - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (_numbers[mid] == numberToSearch)
return true;
else if (_numbers[mid] < numberToSearch)
low = mid + 1;
else
high = mid - 1;
}
return false;
}
The Results
The FasterBinarySearch wins.
Top comments (0)