递归实现二分法

时间:2022-10-27 18:15:10

编写一个F(n) = n*n + (n-1)(n-1) + … + 1 ;

#include<iostream>

using namespace std;


int sum(int n)
{
    if(n == 1){
         return 1;
    }
    int temp = 0;
    temp = (n*n)+ sum(n-1);
    return temp;
}
int main()
{
    int result;

    result = sum(2);


    cout << result <<endl;
     return 0;
}
5
Press any key to continue

用递归实现二分法:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>


#define length 10



using namespace std;

int  find_value(int str[],int left,int right,int value);

int  find_value (int str[],int left,int right,int value)
{

    int med;
    med = (left + right)/2;
    if(left > right){
         return  -1;
    }else {

        if(value > str[med]){
            return  find_value( str ,med+1,right,value);

        }else if(value < str[med]){

          return   find_value (str,left,med -1,value);
        }else{ 

       // printf("find! ");
            return med;

       }

   }

}

int main(int aegc,char **argv)
{

    int str[length] = {0};
    int i;
    for(i =0 ; i < length; i++)
    {
        str[i] = rand()%100;
    }
    int j;
    int k;
    for(j = 1;j<length;j++){
         for(k = j -1;k >= 0 && str[k] > str[k+1];k--)
         {
             int temp =   0;
             temp     = str[k];
             str[k]  = str[k+1];
             str[k+1]   =temp;
         }
    }

    for(i = 0 ; i < length ; i++)
    {
        printf(" %d",str[i]);
    }
    cout <<endl;

       int des =  find_value(str,0,length-1,69);
       printf(" %d is find",des);


    return 0;
}


  0  24  34  41  58  62  64  67  69  78
    8 is findPress any key to continue