三分查找
像这种二分查找,三分查找算法前提都是要在数组有序的情况下,否则就没有意义了
放一个最近练习分治法三分查找的代码:
1 #include<iostream> 2 using namespace std; 3 int a[] = { 0,1,2,3,4,5,6,7,8,9, }; 4 //在区间只有一个数或者两个数的时候采用暴力查找 5 int search(int left, int right, int x) { 6 if (left > right) 7 return -1; 8 else if (left == right) { 9 if (a[left] == x) 10 return left; 11 return -1; 12 } 13 else if (left + 1 == right) { 14 if (a[left] == x) 15 return left; 16 else if (a[right] == x) 17 return right; 18 else 19 return -1; 20 } 21 int len = (right - left + 1) / 3; 22 int p1 = left + len; 23 int p2 = right - len; 24 if (a[p1] == x) 25 return p1; 26 else if (x < a[p1]) 27 return search(left, p1 - 1, x); 28 else if (a[p2] == x) 29 return p2; 30 else if (x < a[p2]) 31 return search(p1 + 1, p2 - 1, x); 32 else 33 return search(p2 + 1, right, x); 34 } 35 int main() { 36 cout<<search(0, 10, 6); 37 38 return 0; 39 }
对于三分查找来说,时间复杂度是log3n,还是log2n级别的