7-5 数据结构实验四 折半查找

建立一个递增的有序表(用顺序表作存储结构),用折半查找的方法对其实施查找。

顺序表的类型描述:

#define MAXSIZE 50
typedef int ElemType;
typedef  struct
{
  ElemType  *R; 
  int  length;
} SSTable;  

输入格式:

第一行输入一个整数n,表示顺序表的元素个数。

第二行行输入n个递增的数字,依次为表内元素值。

第三行输入一个要查找的值。

输出格式:

输出这个值在表中的位置。如果没有找到,输出NOT FOUND

输入样例:

5
2 4 6 8 10
6

输出样例:

3

输入样例:

5
2 4 6 8 10
18

输出样例:

NOT FOUND

代码如下: 

/*#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 50
typedef struct {
    int key;
}SElemType;
typedef  struct
{
    SElemType  *R;
    int  length;
} SSTable;
int Search_Bin(SSTable ST, int key);

int main()
{
    SSTable ST;
    scanf("%d",&ST.length);
    ST.R = (SElemType*) malloc((ST.length+1)*sizeof(SElemType));
    int i;
   for(i=1;i<=ST.length;i++){
       scanf("%d",&ST.R[i].key);
   }
    int key;
    scanf("%d",&key);
    int pos = Search_Bin(ST, key);
    if(pos == -1) puts("NOT FOUND");
    else printf("%d\n", pos);
    return 0;
}
int Search_Bin(SSTable ST, int key){
    int begin = 1,last = ST.length;
    while(begin<=last){
        int mid = (begin+last)/2;
        if(key==ST.R[mid].key){
            return mid;
        }else if(key<ST.R[mid].key){
            last = mid-1;
        }else if(key>ST.R[mid].key){
            begin = mid+1;
        }
    }
    return -1;
}
*/
/*
 * #include<stdio.h>
#include<stdlib.h>
int main(void){
   int i,n,target,index,flag=0;
   int arr[100];
    scanf("%d",&n);
    for(i=1;i<=n;i++){
        scanf("%d",&arr[i]);
    }
    scanf("%d",&target);
    for(i=1;i<=n;i++){
        if(arr[i]==target){
            flag = 0;
            index = i;
            break;
        }else{
            flag = 1;
        }
    }
    if(flag==1){
        printf("NOT FOUND");
    }else{
        printf("%d",index);
    }
    return 0;
}
 * */

#include<stdio.h>
#include<stdlib.h>
typedef  struct
{
    int  *R;
    int  length;
} SSTable;
void Init(SSTable *ST){
    ST->length=0;
    ST->R = (int *) malloc(sizeof(int)*100);
}
int Search_Bin(SSTable ST,int x);
int main(){
    int x;
    SSTable  ST;
    Init(&ST);
    scanf("%d",&ST.length);
    for(int i=1;i<=ST.length;i++){
        scanf("%d",&ST.R[i]);
    }
    scanf("%d",&x);
    int ret = Search_Bin(ST,x);
    if(ret==-1){
        printf("NOT FOUND");
    }else{
        printf("%d",ret);
    }



    return 0;
}
int Search_Bin(SSTable ST,int x){
    int begin = 1,last = ST.length;
    while(begin<=last){
        int mid = (begin+last)/2;
        if(x==ST.R[mid]){
            return mid;
        }else if(x<ST.R[mid]){
            last = mid-1;
        }else if(x>ST.R[mid]){
            begin = mid+1;
        }
    }
    return -1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hu_66666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值