题目
题目分析
二分水题,注意用二分查找的非递归法,我第一遍使用的是递归法,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;
}