2017北京理工大学上机(二):二分查找

任何疑问、意见、建议请留言公众号:一航代码

题目描述:

原题为给出一个非递减数列,写出一个二分查找算法,输出所查找数值的位置及查找次数。在此替换为PAT6-13 折半查找 (15分)

给一个严格递增数列,函数int Search_Bin(SSTable T, KeyType k)用来二分地查找k在数列中的位置。

函数接口定义:

int Search_Bin(SSTable T, KeyType k);

其中T是有序表,k是查找的值。

裁判测试程序样例:

#include <iostream>
using namespace std;

#define MAXSIZE 50
typedef int KeyType;

typedef struct
{
    KeyType key;
} ElemType;

typedef struct
{
    ElemType *R;
    int length;
} SSTable;

void Create(SSTable &T)
{
    int i;
    T.R = new ElemType[MAXSIZE + 1];
    cin >> T.length;
    for (i = 1; i <= T.length; i++)
        cin >> T.R[i].key;
}

int Search_Bin(SSTable T, KeyType k);

int main()
{
    SSTable T;
    KeyType k;
    Create(T);
    cin >> k;
    int pos = Search_Bin(T, k);
    if (pos == 0)
        cout << "NOT FOUND" << endl;
    else
        cout << pos << endl;
    return 0;
}

/* 请在这里填写答案 */

输入格式:

第一行输入一个整数n,表示有序表的元素个数,接下来一行n个数字,依次为表内元素值。然后输入一个要查找的值。

输出格式:

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

输入样例:

5
1 3 5 7 9
7

5
1 3 5 7 9
10

输出样例:

4

NOT FOUND

解决方法:

(1)算法思想:

画图理解:

 

(2)代码实现:

可在https://pintia.cn/problem-sets/14/problems/44932判题

#include <iostream>
using namespace std;

#define MAXSIZE 50
typedef int KeyType;

typedef struct
{
    KeyType key;
} ElemType;

typedef struct
{
    ElemType *R;
    int length;
} SSTable;

void Create(SSTable &T)
{
    int i;
    T.R = new ElemType[MAXSIZE + 1];
    cin >> T.length;
    for (i = 1; i <= T.length; i++) //注意这里下标从1开始,到length
        cin >> T.R[i].key;
}

int Search_Bin(SSTable T, KeyType k); //声明在定义之前

int main()
{
    SSTable T;
    KeyType k;
    Create(T);
    cin >> k;
    int pos = Search_Bin(T, k);
    if (pos == 0)
        cout << "NOT FOUND" << endl;
    else
        cout << pos << endl;
    return 0;
}

int Search_Bin(SSTable T, KeyType k)
{
    int left = 1, right = T.length; //注意下标从1开始,下面while循环不带等号。
    while (left < right)
    {
        int mid = (left + right) / 2; //注意
        if (T.R[mid].key < k)
        {
            left = mid + 1;            //向后二分
        }
        else if (T.R[mid].key > k)
        {
            right = mid - 1;           //向前二分
        }
        else if (T.R[mid].key == k)
        {
            return mid;
        }
    }
    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值