1.顺序查找分为两类,一个是按照元素来查找,即就是看顺序表中是否有与待查元素相同的元素;另外一个就是按照位置来查找,就是找到顺序表中第i个位置的元素
//顺序查找(按数查找) Status FoundList_Sq(SqList L,ElemType e,int i){ int flag=0;//为了后面判断是否在顺序表中找到了这个元素 for(int j=0;j<L.length;j++){ if(L.elem[j]==e){ i=j+1;//判断该元素跟我们要找的元素是否一样 flag=1; break; } } if(flag==0){ printf("没有查到%d元素\n",e); } else printf("元素%d在表中的位置为:%d\n",e,i); return OK; }
//顺序查找(按位查找) Status GetList_Sq(SqList L,int i){ if(i<1||i>L.length)return ERROR; printf("%d位置上的元素是:%d\n",i,L.elem[i-1]); return OK; }
2.这里因为按位置查找元素的时候可以直接用L.elem[i]来表示,所以他的时间复杂度为O(1)
3.总的代码
#include<stdio.h> #include<malloc.h> #include<iostream> #define OK 1 #define ERROR 0 #define OVERFLOW -1 #define LIST_INIT_SIZE 10 #define LISTINCREMENT 100 typedef int ElemType; typedef int Status; typedef struct{ ElemType *elem; int length; int listsize; }SqList; //建立顺序表 Status InitList_Sq(SqList &L,int n){ L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(!L.elem)exit(OVERFLOW); printf("请输入顺序表的元素:"); for(int i;i<n;i++){ scanf("%d",&L.elem[i]); } L.length=n; L.listsize=LIST_INIT_SIZE; return OK; } //输出顺序表 Status ExitList_Sq(SqList L){ for(int i=0;i<L.length;i++){ printf("%d ",L.elem[i]); } printf("\n"); } //顺序查找(按数查找) Status FoundList_Sq(SqList L,ElemType e,int i){ int flag=0;//为了后面判断是否在顺序表中找到了这个元素 for(int j=0;j<L.length;j++){ if(L.elem[j]==e){ i=j+1;//判断该元素跟我们要找的元素是否一样 flag=1; break; } } if(flag==0){ printf("没有查到%d元素\n",e); } else printf("元素%d在表中的位置为:%d\n",e,i); return OK; } //顺序查找(按位查找) Status GetList_Sq(SqList L,int i){ if(i<1||i>L.length)return ERROR; printf("%d位置上的元素是:%d\n",i,L.elem[i-1]); return OK; } int main(){ int n; SqList L; printf("请输入顺序表元素个数:"); scanf("%d",&n); InitList_Sq(L,n); ExitList_Sq(L); int i; ElemType e;//按值查找 printf("请输入想查找的数:"); scanf("%d",&e); FoundList_Sq(L,e,i); int j;//按位查找 printf("请输入想查找的位置:"); scanf("%d",&j); GetList_Sq(L,j); }
4.实验的结果为: