zoukankan      html  css  js  c++  java
  • 顺序查找和二分查找代码

    /*************************************************************************
        > File Name: StaticSearchTable.c
        > Author: 
        > Mail: 
        > Created Time: Fri 21 Dec 2018 03:49:17 PM CST
     ************************************************************************/
    
    #include<stdio.h>
    #define MAXSIZE 20
    
    typedef int keytype;   //自定义关键字类型为整型
    
    typedef struct
    {
        keytype key;
    }ElemType;
    
    typedef struct
    {
        ElemType *elem;
        int length;
    }stable;
    
    void cretable(stable *Q)
    {
        int i;
        keytype x;
        Q->elem = (ElemType *)malloc(sizeof(ElemType)*(MAXSIZE+1));
        printf("Input keys(-1:End):");
        scanf("%d",&x);
        i = 0;
        while(x!=-1 && i<MAXSIZE)
        {
            i++;
            Q->elem[i].key = x;
            scanf("%d",&x);
        }
        Q->length = i;
    }
    
    void list(stable *Q)
    {
        int i;
        for(i=1;i<=Q->length;i++)
        {
            printf("%5d",i);
        }
        printf("
    ");
        for(i=1;i<=Q->length;i++)
        {
            printf("%5d",Q->elem[i].key);
        }
        printf("
    ");
    }
    
    
    //顺序查找
    int seqsearch1(stable *ST,keytype key)
    {
        int i;
        for(i=ST->length;i>0;i--)
        {
            if(ST->elem[i].key==key)return i;
        }
        return 0;
    }
    
    //为了避免查找过程中每一步都要检测整个表是否查找完毕,查找之前先将key付给ST->elem[0]的关键字。
    //改进后如下
    int seqsearch2(stable *ST,keytype key)
    {
        int i;
        ST->elem[0].key = key;
        for(i=ST->length;ST->elem[i].key!=key;i--);
        return i;
    }
    
    //二分查找
    int binsearch(stable *ST,keytype key)
    {
        int low = 1,high = ST->length,mid;
        while(low<=high)
        {
            mid = (low + high)/2;
            if(ST->elem[mid].key==key)return mid;
            if(key<ST->elem[mid].key) high = mid - 1;
            else low = mid + 1;
        }
        return 0;
    }
  • 相关阅读:
    mysql应用技巧
    Python httplib学习
    桌标相关知识
    行业百科知识--Github
    Ghost win7 系统安装(虚拟机)
    记一次pycharm和vscode因网络问题插件下载失败的问题
    Pydiction补全插件
    MS17-010远程溢出漏洞(CVE-2017-0143)
    shell快速入门
    Yarn架构
  • 原文地址:https://www.cnblogs.com/wzqstudy/p/10156579.html
Copyright © 2011-2022 走看看