# 分治策略

1.分治策略的思想

2.分治步骤

3.二分查找

#include<iostream>
using  namespace std;

int searchvalue(int left,int right,int *arr,int x)
{
if(right < 1 || arr == NULL)return -1; //判断一下外界传的参数是否正确
int pos = -1;
if(left <= right)
{
int  mid = (right-left+1)/2+left;
if(x < arr[mid]) return pos = searchvalue(left,mid-1,arr,x);
else if(x >arr[mid]) return pos = searchvalue(mid+1,right,arr,x);
else
{
while(mid > left && arr[mid-1] == x) //这里防止同一个出现多个x,让pos保存最左边的x下标
{
--mid;
}
pos = mid;
}
}
return pos;
}

int main()
{
int arr[] = {12,13,15,17,43,54,67,76,86,90,92};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 15;
int pos = searchvalue(0,n-1,arr,x);
printf("%d\n",pos);
return 0;
}

斐波那契数列

#include<iostream>
using namespace std;

//非递归
int fun(int n)
{
int a = 1, b = 1, c = 1;
int i = 2;
for(i=2; i<n; i++)
{
c = a+b;
a = b;
b =c;
}
return c;
}

//朴素递归
int fun1(int n)
{
if(n <= 2)
{
return 1;
}
return fun(n-2)+fun(n-1);
}

//改良后的递归，时间复杂度比朴素小很多
int fun2(int n,int a,int b)
{
if(n < 3) return a;
else return fun2(n-1,a+b,a);
}

int fac(int n)
{
int a = 1;
int b = 1;
return fun2(n,a,b);
}



05-16
03-12 2万+

02-20 665
03-07 2万+
07-27 3794
07-16 1255
10-15 1150
06-09 2821
06-19 190
10-29 411
03-09 522
11-15 96
03-31 1153
07-30 522
03-28 296
04-23 418
07-11 216
10-04 138