三分查找:
#include
#define M 10
int main(void)
{
int front, near, mid1, mid2;
int n;
int found;
int a[M] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
front = 0;
near = M - 1;
found = 0;
printf("input n:");
scanf("%d", &n);
while(front <= near)
{
mid1 = (near - front) / 3 + front;
mid2 = near - (near - front) / 3;
if(n == a[mid1] || n == a[mid2])
{
found = 1;
break;
}
else if(n < a[mid1])
near = mid1 - 1;
else if(n < a[mid1] && n > a[mid2])
{
front = mid1 + 1;
near = mid2 - 1;
}
else
front = mid2 + 1;
}
if(found = 1 && n == a[mid1])
printf("%d %d", n, mid1);
if(found = 1 && n == a[mid2])
printf("%d %d", n, mid2);
return 0;
}
在我現在認識的層面中,三分查找和二分查找的思想是一樣的,只是比二分查找多了兩個變量,在看博客時,有一位大哥是這麼寫的:
二分是把區間分為長度相等的兩段,三分則是把區間分為長度相等的三段,進行查找,這樣的查找稱為三分查找,三分查找通 常用來迅速確定最值。 眾所周知,二分算法的要求是搜索的序列是單調序列,而三分法所面向的搜索序列的要求是:序列為一個凸性函數。