基础编程题目集 6-13 折半查找 (15分)

在这里插入图片描述
題解:二分

#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;
}
int Search_Bin(SSTable T, KeyType k)
{
    int left = 1;
    int right = T.length;
    int mid = 1;
    bool flag = false;
    while (left < right)
    {
        mid = (left + right) / 2;
        if (T.R[mid].key == k)
        {
            flag = true;
            break;
        }
        if (T.R[mid].key > k)
        {
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }
    if (flag)
    {
        return mid;
    }
    else
    {
        return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值