顺序表应用6:有序顺序表查询
Time Limit: 1000MS Memory Limit: 4096KB
Submit Statistic
Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!”。
Input
第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Example Input
10
1 22 33 55 63 70 74 79 80 87
4
55 10 2 87
Example Output
4
No Found!
No Found!
10
Hint
Author
ThinK:
注意要使用二分查找的方法,不然会超时……
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define LISTINCREASMENT 200020
#define LISTSIZE 100020
#define OVERFLOW -1
#define OK 1
typedef int Elemtype;
typedef struct
{
Elemtype * elem;
int length;
int listsize;
}Sqlist;
int SqInitial(Sqlist &L)
{
L.elem = (Elemtype *)malloc(sizeof(Elemtype)*LISTSIZE);
if(!L.elem)
exit(OVERFLOW);
L.length = 0;
L.listsize = LISTSIZE;
return OK;
}
int ListInsert(Sqlist &L, int i, Elemtype e)
{
if(i<1||i>L.length+1)
return OVERFLOW;
if(L.length>L.listsize)
{
Elemtype*newbase = (Elemtype *)realloc(L.elem, (L.listsize+LISTINCREASMENT)*sizeof(Elemtype));
if(!newbase)
return OVERFLOW;
L.listsize += LISTINCREASMENT;
}
Elemtype *q = &(L.elem[i-1]);
Elemtype *p;
for(p=&(L.elem[L.length-1]);p>=q;p--)
*(p+1) = *p;
*q = e;
L.length++;
return OK;
}
void show(Sqlist &L)
{
for(int i=0;i<L.length-1;i++)
printf("%d ", L.elem[i]);
printf("%d\n", L.elem[L.length-1]);
}
int Find(Sqlist &L, int t, int n, int m)
{
if(n>m)
return -1;
else if(t<L.elem[(n+m)/2])
return Find(L, t, n, (n+m)/2-1);
else if(t>L.elem[(n+m)/2])
return Find(L, t, (n+m)/2+1, m);
else if(t==L.elem[(n+m)/2])
return (n+m)/2;
else
return -1;
}
int main()
{
int a, n, m, t;
scanf("%d", &n);
Sqlist L;
SqInitial (L);
for(int i=1;i<=n;i++)
{
scanf("%d", &a);
ListInsert(L, i, a);
}
scanf("%d", &m);
while(m--)
{
scanf("%d", &t);
int b = Find(L, t, 0, L.length-1);
if(b!=-1)
printf("%d\n", b+1);
else
printf("No Found!\n");
}
return 0;
}
本文介绍了一个基于二分查找实现的算法,用于在一个已排序的顺序表中查询特定整数的位置。文章提供了完整的C语言源代码,并详细解释了如何通过递归方式实现高效的查找过程。
1580

被折叠的 条评论
为什么被折叠?



