题目描述
输入
第二行依次输入n个各不相同的有序整数,代表表里的元素;
第三行输入整数t,代表要查询的次数;
第四行依次输入t个整数,代表每次要查询的数值。
输出
示例输入
10 1 22 33 55 63 70 74 79 80 87 4 55 10 2 87
示例输出
4 No Found! No Found!10
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define LISTINCREASMENT 100 #define LISTSIZE 10 #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 (LISTSIZE*sizeof(ElemType)); if (!L.elem) exit(OVERFLOW); //当前存储空间已满 L.length=0; L.listsize=LISTSIZE; return OK; } int ListInsert(Sqlist &L,int i,ElemType e) // 在顺序表L的第 i 个元素之前插入新的元素e { if(i<1|| i > L.length+1) printf("ERROR!"); 插入位置不合法 if(L.length>=L.listsize) { ElemType*newbase=(ElemType*)realloc(L.elem,(L.listsize+LISTINCREASMENT) *sizeof(ElemType)); if(!newbase) return OVERFLOW;// 当前存储空间已满 L.elem=newbase; 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; // 插入e ++L.length;// 表长增1 return OK; } void print(Sqlist L,int l,int r,int m)//顺序表的快速查找; { int i=l,j=r,k; if(l<=r) { k=(i+j)/2; if(L.elem[k]==m) printf("%d\n",k+1); else if(L.elem[k]>m) print(L,l,k-1,m);//递归的调用; else print(L,k+1,r,m);//递归的调用; } else printf("No Found!\n"); } int main() { int i,j,k,m,n,t; Sqlist L;//顺序表的定义; SqInitial(L);//顺序表的初始化; scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&k); ListInsert(L,i,k);//顺序表元素的插入; } scanf("%d",&t); for(i=0;i<t;i++) { scanf("%d",&m); print(L,0,L.length-1,m);//顺序表元素的查找; } }
#include <iostream> #include<cstdio> using namespace std; int a[20010]; int i,j; int m,n; void print(int a[],int l,int r,int h) { i=l,j=r; int k; if(l<=r) { k=(r+l)/2; if(a[k]==h) printf("%d\n",k+1); else if(a[k]>h) print(a,l,k-1,h); else print(a,k+1,r,h); } else printf("No Found!\n"); } int main() { scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); scanf("%d",&m); int num; while(m--) { scanf("%d",&num); print(a,0,n-1,num); } return 0; }