顺序查找和二分查找代码

/*************************************************************************
    > 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("\n");
    for(i=1;i<=Q->length;i++)
    {
        printf("%5d",Q->elem[i].key);
    }
    printf("\n");
}


//顺序查找
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;
}

 

转载于:https://www.cnblogs.com/wzqstudy/p/10156579.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值