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

问题:为什么if后面第二个else不改成else if就无法通过??求助

以下是接口的定义

Position BinarySearch( List L, ElementType X ); 

List结构的定义

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

L是用户传入的一个线性表,其中ElementType元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数BinarySearch要查找X在Data中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound。

例1:
5
12 31 55 89 101
31

2
例2:
3
26 78 233
31

0

以下为C代码

//错误原因:最后一个else没有设置对条件 
#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();
    scanf("%d", &X);
    P = BinarySearch( L, X );
    printf("%d\n", P);

    return 0;
}
Position BinarySearch(List L,ElementType X)
{
	int p=0;//返回值
	int s=1;//初始位置
	int e=L->Last; 
	while(s<=e)
	{
		int mid=(s+e)/2;
		if(L->Data[mid]==X)
		{
			p=mid;
			break;
		}
		else if(L->Data[mid]>X)
		{
			e=mid-1;
		}
		else if(L->Data[mid]<X) //直接用else 奇偶和首位没有通过
		{
			s=mid+1;
		}
	}
	if(p==0)
	{
		return NotFound;
	}
	return p;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值