普通的顺序查询
#include<iostream>
using namespace std;
int easy_sort(int arr[],int n,int key);
int main(){
int arr[8] = {1,2,3,4,5,6,7,8};
int index=easy_sort(arr,8,4);
cout<<"查找到的索引:" <<index;
}
int easy_sort(int arr[],int n,int key){
for(int i=0;i<n;i++){
if(key==arr[i]) return i;
}
return -1;
}
带有哨兵 的顺序查询
#include<iostream>
using namespace std;
int seq_search(int arr[],int n,int key);
int main(){
int arr[8] = {1,2,3,4,5,6,7,8};
int index=seq_search(arr,8,4);
cout<<"查找到的索引:" <<index;
}
int seq_search(int arr[],int n,int key){
int i=n;
while(arr[i]!=key) i--;
return i;
}