参考视频:
顺序查找和平均查找长度ASL_哔哩哔哩_bilibili
6-21 顺序查找
分数 25
作者 杨嫘
单位 桂林学院
在一个顺序表中找x,输出该数最先出现的位置,没有找到则提示查找失败。
函数接口定义:
int searchSq(SqList L,ElemType x);其中L和x都是用户传入的参数。L是顺序表;x是要查找的元素值。函数须返回该数最先出现的位置,没有找到则返回-1。
裁判测试程序样例:
#include <stdio.h> #define MAXSIZE 1000 typedef int ElemType; typedef struct SqList{ ElemType data[MAXSIZE]; int len; }SqList; void createSq(SqList *L); //输入函数,具体实现略 void printSq(SqList L); //输出函数,具体实现略 int searchSq(SqList L,ElemType x); int main() { SqList L; createSq(&L); int x,n=0; scanf("%d",&x); n=searchSq(L,x); if(n==-1) printf("sorry,can't find it."); else printf("The first place it appears is %d. ",n); } /* 请在这里填写答案 */输入样例1:
6 0 2 4 5 8 9 4输出样例1:
The first place it appears is 2.输入样例2:
10 8 9 5 0 2 4 6 4 11 4 4输出样例2:
The first place it appears is 5.代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C (gcc)
答案
int searchSq(SqList L,ElemType x){ for(int i=0;i<L.len;i++){ if(x==L.data[i]){ return i; } } return -1; }