Problem Description
顺序表内按照由小到大的次序存放着n个互不相同的整数,任意输入一个整数,判断该整数在顺序表中是否存在。如果在顺序表中存在该整数,输出其在表中的序号;否则输出“No Found!"。
Input
第一行输入整数n (1 <= n <= 100000),表示顺序表的元素个数;
第二行依次输入n个各不相同的有序非负整数,代表表里的元素;
第三行输入整数t (1 <= t <= 100000),代表要查询的次数;
第四行依次输入t个非负整数,代表每次要查询的数值。
保证所有输入的数都在 int 范围内。
Output
输出t行,代表t次查询的结果,如果找到在本行输出该元素在表中的位置,否则本行输出No Found!
Sample Input
10 1 22 33 55 63 70 74 79 80 87 4 55 10 2 87
Sample Output
4 No Found! No Found! 10
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct
{
int data[100010];
int len;
}hh;
void creat(hh* h,int n)
{
for(int i=0;i<n;i++){
scanf("%d",&h->data[i]);
}
h->len=n;
}
int find(hh* h,int k,int a,int b)
{
if(a==b&&h->data[a]!=k) return -1;
if(h->data[(a+b)/2]==k) return (a+b)/2;
else if(h->data[(a+b)/2]<k) return find(h,k,(a+b)/2+1,b);
else if (h->data[(a+b)/2]>k) return find(h,k,a,(a+b)/2);
}
int main()
{
hh* a=(hh*)malloc(sizeof(hh));
int n,m,k;
scanf("%d",&n);
creat(a,n);
scanf("%d",&m);
for(int i=0;i<m;i++){
scanf("%d",&k);
int f=find(a,k,0,a->len-1);
if(f==-1) printf("No Found!\n");
else printf("%d\n",f+1);
}
return 0;
}
本文介绍了一个基于顺序表的查找算法实现。通过输入一个已排序的整数列表和待查询的整数,算法能够高效地确定目标整数是否存在于列表中,并返回其位置或提示未找到。文章提供了完整的C++代码实现。
1580

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



