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

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值