PTA 数据结构与算法题目集(中文)6-10
2018-02-01 20:30
525 查看
6-10 二分查找(20 分)
本题要求实现二分查找算法。
函数接口定义:
Position BinarySearch( List Tbl, ElementType K );
其中
List结构定义如下:
typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ };
Tbl是用户传入的一个线性表,其中
ElementType元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数
BinarySearch要查找
K在
Tbl中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记
NotFound。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10#define NotFound 0typedef int ElementType;
typedef int Position; typedef struct LNode *List; struct LNode { ElementType Data[MAXSIZE]; Position Last; /* 保存线性表中最后一个元素的位置 */ };
List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch( List Tbl, ElementType K );
int main()
{
List Tbl;
ElementType K;
Position P;
Tbl = ReadInput();
scanf("%d", &K);
P = BinarySearch( Tbl, K );
printf("%d\n", P);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例1:
5 12 31 55 89 101 31
输出样例1:
2
输入样例2:
3 26 78 233 31
输出样例2:
0
解答:
Position BinarySearch( List Tbl, ElementType K ) { Position low=1; Position high=Tbl->Last; while(low<=high) { Position m 9c87 id=(low+high)/2; if(Tbl->Data[mid]>K) high=mid-1; else if(Tbl->Data[mid]<K) low=mid+1; else return mid; } return NotFound; }
作者: 陈越
单位: 浙江大学
时间限制: 100ms
内存限制: 64MB
代码长
相关文章推荐
- pta-数据结构与算法题目集(中文)-4-3 求链式表的表长
- pta-数据结构与算法题目集(中文)-4-2 顺序表操作集
- PTA 数据结构与算法题目集(中文)6-5
- PTA 数据结构与算法题目集(中文)6-11
- PTA 数据结构与算法题目集(中文)6-1
- PTA 数据结构与算法题目集(中文)6-2
- 数据结构与算法题目集(中文)4-10 二分查找 (20分)
- pta-数据结构与算法题目集(中文)-4-1-单链表逆转
- PTA 数据结构与算法题目集(中文)6-9
- PTA 数据结构与算法题目集(中文)5-4 是否同一棵二叉搜索树 (25分)
- PTA 数据结构与算法题目集(中文)5-5 堆中的路径 (25分)
- PTA 数据结构与算法题目集(中文)5-7 六度空间 (30分)
- PTA 数据结构与算法题目集(中文)5-9 旅游规划 (25分)
- PTA 数据结构与算法题目集(中文)5-8 哈利·波特的考试 (25分)
- PTA 数据结构与算法题目集(中文)5-11 关键活动 (30分)
- pta-数据结构与算法题目集(中文)--4-4 链式表的按序号查找
- PTA 数据结构与算法题目集(中文)6-6
- 数据结构与算法题目集(中文)——5-53 两个有序序列的中位数 (25分)——链表
- PTA 数据结构与算法题目集 5-1 最大子列和问题
- 数据结构与算法题目集(中文)4-11 先序输出叶结点 (15分)