zoukankan      html  css  js  c++  java
  • PTA 6-13 折半查找

    解题的关键是理解题目定义的线性表,这个表下标是从1开始的,所以折半查找的low和high也必须从1和length开始

    #include <iostream>
    using namespace std;
    
    #define MAXSIZE 50
    typedef int KeyType;
    
    typedef  struct                     
    { KeyType  key;                                             
    } ElemType;  
    
    typedef  struct
    { ElemType  *R; 
      int  length;
    } SSTable;                      
    
    void  Create(SSTable &T)
    { int i;
      T.R=new ElemType[MAXSIZE+1];
      cin>>T.length;
      for(i=1;i<=T.length;i++)
         cin>>T.R[i].key;   
    }
    
    int  Search_Bin(SSTable T, KeyType k);
    
    int main () 
    {  SSTable T;  KeyType k;
       Create(T);
       cin>>k;
       int pos=Search_Bin(T,k);
       if(pos==0) cout<<"NOT FOUND"<<endl;
       else cout<<pos<<endl;
       return 0;
    }
    int  Search_Bin(SSTable T, KeyType k) {
        int mid, low = 1, high = T.length;
        while (low <= high) {
            mid = (low + high) / 2;
            if (T.R[mid].key == k) return mid;
            else if (T.R[mid].key > k) high = mid - 1;
            else if (T.R[mid].key < k) low = mid + 1;
        }
        return 0;
    }
  • 相关阅读:
    springMVC
    自动装配
    HTTP Status 500
    this compilation unit is not on the build of a java project
    Struct2提交表单数据到Acion
    ResultMap
    MyEclipse 代码自动提示
    xe mysql
    java Study 基础 1
    InterfaceConnect
  • 原文地址:https://www.cnblogs.com/letwant/p/14279902.html
Copyright © 2011-2022 走看看