zoukankan      html  css  js  c++  java
  • C++ 折半查找

    静态查找表中折半查找算法的实现

    注意:折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列

    #include<iostream>
    using namespace std;
    #define ENDFLAG 10000
    typedef int KeyType;
    typedef char * InfoType;
    typedef struct
    {
     KeyType key;
     InfoType otherinfo;
    }ElemType;
    typedef struct
    {
     ElemType *R;
     int length;
    }SSTable;
    void CreateSTable(SSTable &ST,int n)
    {
     int i;
     ST.R=new ElemType[n+1];
     cout<<"请输入"<<n<<"个测试数据:";
     for(i=1;i<=n;i++)
      cin>>ST.R[i].key; 
     ST.length=n;
    }
    int Search_Bin1(SSTable ST,KeyType key)
    {
     int low,high,mid;
     low=1;
     high=ST.length;
     while(low<=high)
     {
      mid=(low+high)/2;
      if(key==ST.R[mid].key) return mid;
      else if(key<ST.R[mid].key) high=mid-1;
      else low=mid+1;
     }
     return 0;
    }
    int Search_Bin2(SSTable ST,int low,int high,KeyType key)
    {
     int mid;
     if(low>high) return 0;
     mid=(low+high)/2;
     if(key==ST.R[mid].key) return mid;
     else if(key<ST.R[mid].key) return Search_Bin2(ST,low,mid-1,key);
     else return Search_Bin2(ST,mid+1,high,key);
    }

    void main()
    {
     int n;
     KeyType key;
     SSTable ST;
     cout<<"请输入静态查找表长:";
     cin>>n;
     CreateSTable(ST,n);
     cout<<"请输入待查记录的关键字:";
     cin>>key;
     cout<<"Search_Bin1算法计算的位置为:"<<Search_Bin1(ST,key)<<endl;
     cout<<"Search_Bin2算法计算的位置为:"<<Search_Bin2(ST,1,ST.length,key)<<endl;
    }

    态度成就高度,技术实现梦想
  • 相关阅读:
    iis 5.0 不能运行 asp.net 的 原因
    股票在线讨论
    adsl 加 路由器 网关不能上网的 原因
    汽车英语
    势与子的辩证法
    中国上海的黑心培训学校
    excel 里的 图表的使用
    带宽 下载速度 比特 率 换算 速度
    硬盘分区表修复秘籍
    Bootstrap a标签的单击时停止传播事件
  • 原文地址:https://www.cnblogs.com/YY-Xcode/p/4958204.html
Copyright © 2011-2022 走看看