第14週プロジェクト--1.半角検索

1459 ワード

/*Copyright(c)2015、煙台大学コンピュータと制御工学学院*All rights reserved*著者:李宗政*完成日:2015年11月30日*バージョン番号:V 1.0*コンテンツの説明:半角検索を使用して、対応する要素を検索します*/
 
しゅかんすう
#include <stdio.h>
#define MAXL 100
typedef int KeyType;
typedef char InfoType[10];
typedef struct
{
    KeyType key;                //KeyType         
    InfoType data;              //    
} NodeType;
typedef NodeType SeqList[MAXL];     //     

int BinSearch(SeqList R,int n,KeyType k)
{
    int low=0,high=n-1,mid;
    while (low<=high)
    {
        mid=(low+high)/2;
        if (R[mid].key==k)      //      
            return mid+1;
        if (R[mid].key>k)       //   R[low..mid-1]   
            high=mid-1;
        else
            low=mid+1;          //   R[mid+1..high]   
    }
    return 0;
}

int main()
{
    int i,n=10;
    int result;
    SeqList R;
    KeyType a[]= {1,3,9,12,32,41,45,62,75,77},x=62;
    for (i=0; i<n; i++)
        R[i].key=a[i];
    result = BinSearch(R,n,x);
    if(result>0)
        printf("     %d    %d
",result, x); else printf(" !
"); return 0; }

出力結果
 
 
 
 
 
まとめ:折半ルックアップ法を用いると,順序ルックアップ法よりも1つの数字を見つけるのが速い場合が多いが,順序ルックアップ法が速い場合もある.