二分查找和快速幂
二分主要考察的是思想、快速幂是递归。
二分:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10;
int arr[maxn];
int search(int* arr, int x, int y, int v){
/*
二分思想;
代码实现的话,这是一个循环的过程,有上界和下界, 每次查找都会改变上界
或者下界, 循环结束的条件就是下届超过上界。
就是把要查找的序列,先排序,然后每次就假设中间位置的值是答案,
如果非答案,就和答案相比较, 根据和答案大小的相比,改变上下界。
*/
int m;
while(x < y){
// 中点
m = x + (y - x ) / 2;
// 如果是答案
if(arr[m] == v) return m;
else if(arr[m] > v ) y = m;// 答案比中点值要小, 改变上界
else x = m+ 1; // 答案比中点值要大, 改变下界
}
return -1;
}
int main(){
for(int i=0;i<maxn;i++)
cin>>arr[i];
sort(arr, arr+maxn);
for(int i=0;i<maxn;i++)
cout<<arr[i]<<" "<<endl;
int ans = search(arr, 0, maxn-1, 5);
cout<<" 位置: "<< ans <<endl;
return 0;
}
快速幂:
#include <iostream>
using namespace std;
typedef long long ll;
ll binaryPow(ll a, ll b){
// 递归的终止条件
if( b == 0 ) return 1;
// 递归调用的开始
if( b % 2 == 1){
return a * binaryPow(a, b-1);
}else{
ll num = binaryPow(a, b / 2);
return num * num;
}
}
int main(){
ll a, b;
cin>>a>>b;
ll ans = binaryPow(a, b);
cout<< ans <<endl;
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容