二分查找与三分查找算法 C#
首先是二分查找法,时间复杂度O(2log2(n)):
static bool Find(int[] sortedArray, int number)
{
if (sortedArray.Length == 0)
return false;
int start = 0;
int end = sortedArray.Length - 1;
while (end >= start)
{
int middle = (start + end) / 2;
if (sortedArray[middle] < number)
start = middle + 1;
else if (sortedArray[middle] > number)
end = middle - 1;
else
return true;
}
return false;
}
然后是三分查找算法,时间复杂度O(3log3(n)):
static bool Find(int[] sortedArray, int number)
{
if (sortedArray.Length == 0)
return false;
int start = 0;
int end = sortedArray.Length - 1;
while (end >= start)
{
int firstMiddle = (end - start) / 3 + start;
int secondMiddle = end - (end - start) / 3;
if (sortedArray[firstMiddle] > number)
end = firstMiddle - 1;
else if (sortedArray[secondMiddle] < number)
start = secondMiddle + 1;
else if (sortedArray[firstMiddle] != number && sortedArray[secondMiddle] != number)
{
end = secondMiddle - 1;
start = firstMiddle + 1;
}
else
return true;
}
return false;
}
对比可以发现,三分查找算法的时间复杂度要比二分查找算法的时间复杂度低,但是实际上效率并没有二分查找算法高,因此我们不能过于迷信一个算法的时间复杂度。