顺序表应用6:有序顺序表查询
Time Limit: 7MS Memory Limit: 700KB
Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数(1<=n<=20000),任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!”。
Input
第一行输入整数n,表示顺序表的元素个数;
第二行依次输入n个各不相同的有序整数,代表表里的元素;
第三行输入整数t,代表要查询的次数;
第四行依次输入t个整数,代表每次要查询的数值。
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
#include <stdio.h>
#include <stdlib.h>
#define MAXN 20004
typedef struct node
{
int date[MAXN];
int last;
}st;
st *l;
st * makeempty()//顺序表的初始化
{
l = (st *)malloc(sizeof(st));
l->last = -1;
return l;
}
st * build(st *l)//顺序表内元素的建立
{
int i;
for(i = 0; i <= l->last; i++)
{
scanf("%d", &l->date[i]);
}
return l;
}
int search(st *l, int left, int right, int ans)//通过二分法在有序顺序表中查询
{
int mid = (left + right)/2;
if(ans < l->date[left] || ans > l->date[right])
{
return -1;
}
if(ans == l->date[mid])
{
return (mid+1);
}
if(ans > l->date[mid])
{
left = mid + 1;
}
if(ans < l->date[mid])
{
right = mid - 1;
}
return search(l, left, right, ans);
}
int main()
{
int n, T, x, y;
l = makeempty();//调用顺序表初始化函数
scanf("%d", &n);
l->last = n-1;
l = build(l);//调用顺序表元素建立函数
scanf("%d", &T);
while(T--)
{
scanf("%d", &x);
y = search(l, 0, n-1, x);//调用有序顺序表二分法查找函数
if(y != -1)
{
printf("%d\n", y);
}
else if(y == -1)
{
printf("No Found!\n");
}
}
return 0;
}
/***************************************************
User name: jk160630
Result: Accepted
Take time: 16ms
Take Memory: 196KB
Submit time: 2017-01-21 11:12:46
****************************************************/
hint:注意顺序表的初始化