例如,我们为什么不n/3
代替n/2
使用n/2
的二进制搜索的递归关系是
T(n) = T(n/2) + C
可以简化为
log2(m) = n
和n/3
T(n) = T(n/3) + C
可以简化为
log3(m) = n
所以我的问题是:自log3(m) < log2(m)
以来为什么我们使用n/2
答案 0 :(得分:1)
三元搜索确实比二元搜索(log3(m) < log2(m))
具有更少的递归调用,但三元搜索在最坏情况下比二元搜索有更多的比较。
进一步研究一下,让我们比较一下C ++中的二进制和三元搜索算法
二进制搜索
// A recursive binary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (arr[mid] == x) return mid;
// If element is smaller than mid, then it can only be present
// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present in array
return -1;
}
三元搜索
// A recursive ternary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int ternarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid1 = l + (r - l)/3;
int mid2 = mid1 + (r - l)/3;
// If x is present at the mid1
if (arr[mid1] == x) return mid1;
// If x is present at the mid2
if (arr[mid2] == x) return mid2;
// If x is present in left one-third
if (arr[mid1] > x) return ternarySearch(arr, l, mid1-1, x);
// If x is present in right one-third
if (arr[mid2] < x) return ternarySearch(arr, mid2+1, r, x);
// If x is present in middle one-third
return ternarySearch(arr, mid1+1, mid2-1, x);
}
// We reach here when element is not present in array
return -1;
}
在最糟糕的情况下,二进制搜索会进行2log2(n) + 1
比较,其中三元搜索执行4log3(n) + 1
比较
比较归结为log2(n)
和2log3(n)
更改基数2log3(n) = (2 / log2(3)) * log2(n)
由于(2 / log2(3)) > 1
Ternay搜索在最坏的情况下进行了更多的比较