函数题 01-复杂度3 二分查找【PAT】
文章目录
- 题目
- 函数接口定义
- 裁判测试程序样例
- 输入样例1
- 输出样例1
- 输入样例2
- 输出样例2
- 题解
- 解题思路
- 完整代码
- AC代码
编程练习题目集目录
题目
本题要求实现二分查找算法。
函数接口定义
Position BinarySearch( List L, ElementType X );
其中 L i s t List List 结构定义如下:
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
L L L是用户传入的一个线性表,其中 E l e m e n t T y p e ElementType ElementType 元素可以通过 > 、 = = 、 < >、==、< >、==、< 进行比较,并且题目保证传入的数据是递增有序的。函数 B i n a r y S e a r c h BinarySearch BinarySearch 要查找 X X X 在 D a t a Data Data 中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记 N o t F o u n d NotFound NotFound。
裁判测试程序样例
#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;
}
/* 你的代码将被嵌在这里 */
输入样例1
5
12 31 55 89 101
31
输出样例1
2
输入样例2
3
26 78 233
31
输出样例2
0
题解
解题思路
按照二分查找算法的思路对
L
i
s
t
List
List 中的数据进行查找,具体查找思路可参考:查找算法,如果查找到目标数字,则直接返回其下标,如果没有找到则返回
N
o
t
F
o
u
n
d
NotFound
NotFound (定义为
0
0
0);
注:为了方便测试及代码完整性,对裁判实现的部分进行了模拟实现(有添加变量)。
完整代码
#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; /* 保存线性表中最后一个元素的位置 */
};
int N;
List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch(List L, ElementType X);
int main(void)
{
List L;
Position P;
ElementType X;
printf("请输入要输入的数字个数:\n");
scanf("%d", &N);
L = ReadInput();
printf("请输入整数要查找的数字:\n");
scanf("%d", &X);
P = BinarySearch(L, X);
printf("%d\n", P);
return 0;
}
List ReadInput() { // 为了代码完整性,模拟实现 ReadInput() 函数
List L = (List)malloc(sizeof(struct LNode)); // 分配内存
if (L == NULL) {
printf("内存分配失败!\n");
exit(1);
}
L->Last = 0; // 初始化为空表
int count = 0;
int value;
printf("请输入 %d 个整数:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &value);
L->Last++;
L->Data[L->Last] = value;
count++;
}
if (count == MAXSIZE) {
printf("警告:输入数据已达到最大容量 %d,剩余数据将被忽略。\n", MAXSIZE);
}
return L;
}
/* 你的代码将被嵌在这里 */
Position BinarySearch(List L, ElementType X) {
int head = 1;
int end = L->Last;
while (head <= end) {
int mid = (head + end) / 2;
if (L->Data[mid] == X) {
return mid; // 找到要查找的数字
}
else if (L->Data[mid] > X) {
end = mid - 1;
}
else {
head = mid + 1;
}
}
return NotFound; // 未找到要查找到数字,返回0
}
AC代码
Position BinarySearch(List L, ElementType X) {
int head = 1;
int end = L->Last;
while (head <= end) {
int mid = (head + end) / 2;
if (L->Data[mid] == X) {
return mid; // 找到要查找的数字
}
else if (L->Data[mid] > X) {
end = mid - 1;
}
else {
head = mid + 1;
}
}
return NotFound; // 未找到要查找到数字,返回0
}