查找

实验项目名称:查找

实验目的及要求:实验目的
(1)理解顺序表的二分查找算法。
(2)实现顺序表的二分查找算法
要求:
(1)设计一顺序表的存储结构;
(2)数据元素为整数类型;
(3)在实现顺序表的二分查找算法

实验原理:
前提条件:查找表中的所有记录是按关键字有序(升序或降序) 。
查找过程中,先确定待查找记录在表中的范围,然后逐步缩小范围(每次将待查记录所在区间缩小一半),直到找到或找不到记录为止。
首先将待查的K值与有序表R[0]到R[n-1]的中间位置mid上的结点的关键字进行比较,
 若相等,则查找完成;
 否则,若 R[mid].key>K,则说明待查找的结点只可能在左子表R[0]到R[mid-1]中,只需在左子表中继续查找;
 否则在右子表中继续查找。
经过一次关键字的比较就缩小了一半的查找区间。如此进行下去,直到找到为止(也存在最后找不到的可能)。
实验内容(方法和步骤):
通过键盘接收数据,将数据存入查找表中。
测试用例:(1,10,20,30,35,40,45,50,58,60,70)。
查找:20。
实验步骤:
(1)接收十进制整数建立查找表。
(2)接收要查找的十进制整数。
(3)输出查找数据在查找表中的位置,并显示查找表。

实验结果与分析:
(1)分析实验中所遇到的问题,自己的解决思路及实现方法。
(2)写出自己所用的测试用例,并记录结果。
(3)总结本次实验的收获。
代码实现

#include <stdio.h>
#include "stdlib.h"


// create a search table. the function will return the length of the table.
int createSearchTable(int **s){
    printf("please enter the length of the the search table.\n");
    int len = 0;
    scanf_s("%d", &len);
    *s = (int *)malloc(sizeof(int) * len);
    printf("please enter the elements:\n");
    for (int i = 0; i < len; ++i) {
        scanf_s("%d", (*s)+i);
    }
    return len;
}


// binary search algorithm. print the position of the key, if ot exists, otherwise print "there is not the key %d\n", key"
void binSearch(int *s, int key, int len){
    int low = 0, high = len-1; // set the initial value of the search interval.
    while (low <= high){
        int mid = (low + high)/2;
        // find the key.
        if(*(s+mid)==key){
            printf("the position is %dth\n", mid + 1);
            return;
        }else{
            // continue the search in the second half of the interval.
            if(*(s+mid) < key){
                low = mid + 1;
                // continue the search in the first half of the interval.
            } else{
                high = mid - 1;
            }

        }
    }
    printf("there is not the key %d\n", key);
}


void visit(int *s, int len){
    // traverse the table.
    printf(" the traverse of the array:\n");
    for (int i = 0; i < len; ++i) {
        printf("%d ",*(s + i));
    }
    printf("\n");
}

int main() {
    int *s = NULL;
    int len = createSearchTable(&s);
    printf("--------------------\n");
    int key = 0;
    // test bin-search
    for (int i = 0; i < 2; ++i) {
        printf("please enter the key that you will be search\n");
        scanf_s("%d", &key);
        binSearch(s, key, len);
        printf("--------------------\n");
    }
    visit(s, len);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值