您的位置:首页 > 其它

MIT:算法导论——3.分治法实例_二分查找 和求a^b

2014-06-05 10:20 260 查看
#if 0

基本的知识在上一节有介绍。本节补充:

分治法: (1)“分” (2)“治” (3)“合并”

线性时间(linear time):一个元素用一个时间,n个元素用n个时间。

递归中,如果自上而下有重复,那么可以采用自下而上计算。即正向迭代。

数学归纳法来证明:Induction Fib数列可以用矩阵乘法来实现。

超大规模集成电路:VLSI(very large scale integrated)

高度H(n):Height, 宽度W(n):Width。

最后为什么是L(n) = 2L(n/4) + O(1),n/4是怎么来的

【本课例子】

(1)二分查找

(2)求a^b

#endif

#if 0

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

//struct LOC{

// int low;

// int high;

// LOC& operator=( LOC& rhs ){

// this->low = rhs.low;

// this->high = rhs.high;

// return *this;

// }

//};

template<typename T>

int find_binary_array( T a[], int low, int high, T key);

int power_my( int a, int b );

int main( void )

{

cout << "2014-6-4 15:56:57" << endl;

int a[] = { -4, -3, -2, 2, 3, 6, 13, 18, 20, 27, 32, 35, 42, 45, 54, 57 };

int loc;

loc = find_binary_array<int>( a, 0, sizeof( a ) / sizeof( int ), 27 );

cout << loc << endl;

loc = find_binary_array<int>( a, 0, sizeof( a ) / sizeof( int ), 60 );

cout << loc << endl;

cout << power_my( 2, 10 ) << endl;

return 0;

}

template<typename T>

int find_binary_array( T a[], int low, int high, T key)

{// 对升序数组进行二分查找

if( a == NULL || low > high )

return -1;

int mid;

while( low <= high ){

mid = ( low + high ) / 2;

if( a[mid] == key )

return mid;

else if( a[mid] > key )

high = mid - 1;

else

low = mid + 1;

}

return -1;

}

int power_my( int a, int b )

{

if( b == 1 )

return a;

int c;

c = power_my( a, b / 2 );

c *= c;

if( b % 2 != 0 )

c *= a;

return c;

}

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: