数据结构与算法题目集(中文)4-10 二分查找 (20分)
来源:互联网 发布:城市智能交通大数据 编辑:程序博客网 时间:2024/04/23 18:30
4-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:
512 31 55 89 10131
输出样例1:
2
输入样例2:
326 78 23331
输出样例2:
0
// 4-10 二分查找 (20分)#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;}/* 你的代码将被嵌在这里 */Position BinarySearch(List Tbl, ElementType K) {int left;int right;if (Tbl->Last) {left = 1;right = Tbl->Last; while(left <= right) {if (K == Tbl->Data[(left + right) / 2])return (left + right) / 2;else {if (K < Tbl->Data[(left + right) / 2])right = (left + right) / 2 - 1;else left = (left + right) / 2 + 1;}}}return NotFound;}
0 0
- 数据结构与算法题目集(中文)4-10 二分查找 (20分)
- PTA数据结构与算法题目集(中文)4-10 二分查找 (20分)
- PTA数据结构与算法题目集(中文)4-4 链式表的按序号查找 (10分)
- PTA数据结构与算法题目集(中文)4-2 顺序表操作集 (20分)
- PTA数据结构与算法题目集(中文)4-5 链式表操作集 (20分)
- PTA数据结构与算法题目集(中文)4-1 单链表逆转 (20分)
- PTA数据结构与算法题目集(中文)4-8 求二叉树高度 (20分)
- PTA 数据结构与算法题目集(中文)5-10 公路村村通 (30分)
- 数据结构与算法题目集(中文)4-9 二叉树的遍历 (25分)
- 数据结构与算法题目集(中文)4-11 先序输出叶结点 (15分)
- PTA数据结构与算法题目集(中文)4-9 二叉树的遍历 (25分)
- PTA数据结构与算法题目集(中文)4-6 带头结点的链式表操作集 (20分)
- PTA数据结构与算法题目集(中文)4-7 在一个数组中实现两个堆栈 (20分)
- PTA数据结构与算法题目集(中文)4-3 求链式表的表长 (10分)
- 数据结构与算法(10)二分查找
- PTA 数据结构与算法题目集(中文)5-6 列出连通集 (25分)
- PTA 数据结构与算法题目集(中文)5-3 树的同构 (25分)
- PTA 数据结构与算法题目集(中文)5-5 堆中的路径 (25分)
- ListView和Adapter Crash问题的分析和解决
- 微软面试百题005——SBT再解第K数问题
- 通过socket登陆MySQL
- 【Python】|JSON序列化与反序列化
- jquery change()时间
- 数据结构与算法题目集(中文)4-10 二分查找 (20分)
- android中的mvp模式(二)
- c++ 函数模板 类模板
- (*(volatile unsigned long *) 地址)
- Canvas裁剪和Region、RegionIterator
- Quartz+Spring 分布式定时任务调度(一)- 环境搭建
- 图形视图框架(The QGraphics View Framework)
- scws自定义分词库
- python generator yield 协程 coroutine