码迷,mamicode.com
首页 > 编程语言 > 详细

对数复杂度算法

时间:2015-10-25 22:15:21      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:

  二分搜索(binary search):给定一个整数X和整数A1,A1,...,AN-1,后者已经预先排序并在内存中,求下标 i 使得 Ai = X,如果X不在数据中,则返回-1。

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 const int NOT_FOUND = -1;
 6 template <typename Comparable>
 7 int binarySearch(const vector<Comparable> &a, const Comparable &x) {
 8     int low = 0, high = a.size() - 1;
 9     while(low <= high) {
10         int mid = (low + high) / 2;
11         if(a[mid] < x) {
12             low = mid + 1;
13         } else if(a[mid] > x) {
14             high = mid - 1;
15         } else {
16             return mid;
17         }
18     }
19     return NOT_FOUND;
20 }    //时间复杂度为O(logN)
21 
22 int main() {
23     vector<int> a;
24     for(int i = 0; i < 20; ++i) {
25         a.push_back(i * 2);
26     }
27     int mid;
28     mid = binarySearch(a, 16);
29     cout << mid << endl;
30     return 0;
31 }

 

欧几里得算法

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 long gcd(long m, long n) {
 6     //欧几里得算法
 7     //m大于等于n
 8     while(n != 0) {
 9         long rem = m % n;
10         m = n;
11         n = rem;
12     }
13     return m;
14 }    //时间复杂度为O(logN)
15 
16 int main() {
17     cout << gcd(50, 15) << endl;
18     cout << gcd(1989, 1590) << endl;
19     return 0;
20 }

幂运算:如果N是偶数,XN = XN/2 * XN/2,如果N是奇数,则XN = X(N-1)/2 * X(N-1)/2 * X。

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 long pow(long x, int n) {
 6     if(n == 0)
 7         return 1;
 8     if(n == 1) 
 9         return x;
10     if(n%2 == 0)
11         return pow(x * x, n/2);
12     else 
13         return pow(x * x, n/2) * x;
14 }
15 
16 int main() {
17     cout << pow(2, 10) << endl;
18     cout << pow(2, 7) << endl;
19     return 0;
20 }

第11行若替换为 return pow(pow(x * x, 2), n/2); 或 return pow(pow(x, n/2), 2); ,当n是2时,程序会产生一个无限循环。

当第11行替换为 return pow(x, n/2) * pow(x, n/2); 时,会影响程序的效率。

对数复杂度算法

标签:

原文地址:http://www.cnblogs.com/wjq-Law/p/4901592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!