PTA 01-复杂度3 二分查找

题目

01-复杂度3 二分查找 (20 分)

题目分析

二分水题,注意用二分查找的非递归法,我第一遍使用的是递归法,TLE了。。。

代码实现

Position BinarySearch( List L, ElementType X )
{
    Position start,last,mid;//一定要注意用Position定义
    start=1;
    last=L->Last;
    while(start<=last)
    {
        mid=(start+last)/2;
        if(X==L->Data[mid])
            return mid;
        else if(X<L->Data[mid])
            last=mid-1;
        else
            start=mid+1;
    }
    return NotFound;
}

附(仅供参考)

二分查找的递归法代码(函数)

Position find_(int start,int last,List L,ElementType x)//递归函数
{
    int mid=(start+last)/2;
    if(start>last)//注意结束条件
        return NotFound;
    else
    {
        if(x==L->Data[mid])//写链表,不是mid
            return mid;
        else if(x<L->Data[mid])//注意改变last
            return find_(start,mid-1,L,x);
        else if(x>L->Data[mid])
            return find_(mid+1,last,L,x);
    }
}

Position BinarySearch( List L, ElementType X )
{
    int start,last;
    start=1;
    last=L->Last;
    return find_(start,last,L,X);
}

完整程序代码(供测试函数)

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

#define MAXSIZE 10
#define NotFound 0
typedef int ElementType;

typedef int Position;
typedef struct LNode *List;
struct LNode
{
    ElementType Data[MAXSIZE];
    Position Last; /* 保存线性表中最后一个元素的位置 */
};

List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch( List L, ElementType X );

int main()
{
    List L;
    ElementType X;
    Position P;

    L = ReadInput();
    printf("请输入要查找的数字:");
    scanf("%d", &X);
    P = BinarySearch( L, X );
    printf("%d\n", P);

    return 0;
}

List ReadInput()
{
    int n;
    List l=(List)malloc(sizeof(LNode));
    printf("请输入数字数目:");
    scanf("%d",&n);
    printf("请输入数字:");
    for(int i=1; i<=n; ++i)
        scanf("%d",&(l->Data[i]));
    l->Last=n;
    return l;
}

Position BinarySearch( List L, ElementType X )
{
    Position start,last,mid;//一定要注意用Position定义
    start=1;
    last=L->Last;
    while(start<=last)
    {
        mid=(start+last)/2;
        if(X==L->Data[mid])
            return mid;
        else if(X<L->Data[mid])
            last=mid-1;
        else
            start=mid+1;
    }
    return NotFound;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值