zoukankan      html  css  js  c++  java
  • 数据结构与算法(C++)之折半查找递归算法

    折半查找递归算法跟迭代算法:

    #include <iostream>
    using namespace std;
    int diedai(int *a,const int x,const int n);
    int digui(int *a,const int x,const int left,const int right);
    int main()
    {
    int a[]={1,2,3,4,5,6,7,8,9,10};

    int num=1;
    //9为数组的下标
    int o=digui(a,num,0,9);
    if(o<0)
    cout<<"递归:对不起没有找到!"<<endl;
    else
    cout<<"递归:在a["<<o<<"]中找到"<<num<<endl;
    //10为数据的个数
    int b=diedai(a,num,10);
    if(b<0)
    cout<<"迭代:对不起没有找到!"<<endl;
    else
    cout<<"迭代:在a["<<o<<"]中找到"<<num<<endl;
    return 0;
    }
    int diedai(int *a,const int x,const int n){
    int left=0,right=n-1;
    while(left<=right){
    int mid=(left+right)/2;
    if(x<a[mid]) right=mid-1;
    else if(x>a[mid]) left=mid+1;
    else return mid;
    }
    return -1;
    }
    int digui(int *a,const int x,const int left,const int right){
    if(left<=right){
    int mid=(left+right)/2;
    if(x<a[mid]) return digui(a,x,left,mid-1);
    else if(x>a[mid]) return digui(a,x,mid+1,right);
    else return mid;
    }
    return -1;
    }

    no one and you
  • 相关阅读:
    poj 1654(利用叉积求面积)
    poj 3230(初始化。。动态规划)
    hdu 1392(凸包)
    hdu 1348(凸包)
    hdu 1147(线段相交)
    hdu 1115(多边形重心问题)
    POJ 2373 Yogurt factory
    GCJ 2008 APAC local onsites C Millionaire
    FZU 1397 保送
    FZU 1064 教授的测试
  • 原文地址:https://www.cnblogs.com/wslQAQ/p/12330025.html
Copyright © 2011-2022 走看看