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;
    }
  • 相关阅读:
    mmap函数实现
    linux交换空间
    日志式文件系统
    Linux内核书籍
    进程状态
    form表单中enctype="multipart/form-data"的作用
    php导入excel表格
    什么是隐藏域
    把生成的excel文件直接提供为下载页效果
    到底什么是实例化
  • 原文地址:https://www.cnblogs.com/wzqstudy/p/10156579.html
Copyright © 2011-2022 走看看