zoukankan      html  css  js  c++  java
  • 基于线性表的哨兵查找和折半查找

    #include<stdio.h>
    typedef int KeyType;
    #define LIST_SIZE 20
    typedef struct RecordType
    {
    KeyType key;
    //OtherType other_data;
    }RecordType;


    typedef struct RecordList
    {
    RecordType r[LIST_SIZE+1];
    int length;
    }RecordList;


    void Init(RecordList *l,KeyType k)
    {
    l->r[0].key=0;
    RecordType r[LIST_SIZE+1];
    printf("请输入长度:");
    scanf("%d",&l->length);
    for(int i=1;i<l->length;i++)
    {
    printf("输入序列中元素:");
    scanf("%d",&l->r[i].key);
    }
    /* for(i=1;i<l.length;i++)
    {
    printf("初始化的序列为%d ", l.r[i].key);
    }*/
    }


    //哨兵查找
    int SeqSearch(RecordList l,KeyType k)
    {
    int i;
    i=l.length;
    while(i>=1&&l.r[i].key!=k)
    {
    i--;
    }
    if(i>=1)return i;
    else return 0;
    }

    //折半查找
    int BinSearch(RecordList l,KeyType k)
    {
    int low,mid,high;
    low=1;
    high=l.length;
    printf("请输入要查找的值:");
    scanf("%d",&k);
    while(low<=high)
    {
    mid=(low+high)/2;
    if(k==l.r[mid].key)
    {
    return (mid);
    }
    else if(k<l.r[mid].key)
    {
    high=mid-1;
    }
    else low=mid+1;
    }
    return 0;
    }

    void main()
    {
    RecordList l;KeyType k;
    int i,result1,result2;
    Init(&l,k);
    printf("请选择:---1.哨兵查找。2.折半查找。 ");
    scanf("%d",&i);
    switch(i)
    {
    case 1:
    result1=SeqSearch(l,k);
    printf("%d ",result1);
    case 2:
    result2=BinSearch(l,k);
    printf("%d ",result2);
    default:
    printf("Error!");
    }
    }

  • 相关阅读:
    帮朋友写的两篇文章
    与疯姐的对话
    实现C(i,j)=A(m,n,w)+B(m,n)
    误差处理相关
    http://blog.sina.com.cn/s/blog_4aae007d0100inxi.html
    全局变量和局部变量
    Yeelink:将复杂的传感器以极简的方式组到同一个网络内
    基站分布:GDOP
    C++学习路线图
    Matlab中三点确定质心
  • 原文地址:https://www.cnblogs.com/yjm5/p/6129450.html
Copyright © 2011-2022 走看看