順序表的順序查找


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.實驗的結果為:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM