为了蓝桥杯,PTA,为了未来
01-复杂度3 二分查找
无
#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 tleft,int tright );
Position BinarySearch2(List L,ElementType X);
int main()
{
List L;
ElementType X;
Position P;
L = ReadInput();
scanf("%d", &X);
P = BinarySearch2( L, X );
//P = BinarySearch( L, X ,1,L->Last);
printf("%d\n", P);
return 0;
}
/* 你的代码将被嵌在这里 */
List ReadInput(){
List L;
int i;
L = (List)malloc(sizeof(struct LNode));
L->Data[0] = 0;
scanf("%d", &L->Last);
for (i=1; i<=L->Last; i++)
scanf("%d", &L->Data[i]);//该readinput不使用数组的第零个
return L;
}
Position BinarySearch( List L, ElementType X,int tleft,int tright )
{
int mid=(tleft+tright)/2;
if(tleft>tright)
return NotFound;
if(X<L->Data[mid])
{
return BinarySearch(L,X,tleft,mid-1);
}
else if(X>L->Data[mid])
{
return BinarySearch(L,X,mid+1,tright);
}
return mid;
}
Position BinarySearch2(List L,ElementType X)
{
int left,right,mid;
left=1;
right=L->Last;
while(left<=right)
{
mid=(left+right)/2;
if(X<L->Data[mid])
{
right=mid-1;
}else if(X>L->Data[mid])
{
left=mid+1;
}else
return mid;
}
return NotFound;
}
两种法子:一种递归(但是四个参数 一种while(两个参数