检索问题
1. 问题
检索是指从用户特定的信息需求出发,对特定的信息集合采用一定的方法、技术手段,根据一定的线索与规则从中找出相关信息。
检索问题是查找集合中是否存在需要查找的内容。
2. 解析
顺序检索是按元素的下标位置,按照顺序判断该数组是否存在需要查找的元素。因此只需要对整个数组遍历一遍即可。
二分检索要求存储结构必须采用顺序存储结构,而且结构中元素按关键字有序排列。首先,假设表中元素是按升序排列,将表中间位置记录记录与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
3. 设计
顺序检索:
1 #include<stdio.h> 2 const int maxn= 1000 + 10; 3 int T[maxn]; 4 int n; 5 /*----------以下为顺序检索----------*/ 6 int Inorder(int x){ 7 int pos=0; 8 for(int i=1;i<=n;++i){ 9 if(T[i]==x){ 10 pos=i; 11 break; 12 } 13 } 14 return pos; 15 } 16 /*----------以上为顺序检索----------*/ 17 int main(){ 18 scanf("%d",&n); 19 for(int i=1;i<=n;++i)scanf("%d",&T[i]); 20 int x; 21 scanf("%d",&x); 22 printf("下标j=%d ",Inorder(x)); 23 }
二分检索:
1 #include<stdio.h> 2 const int maxn= 1000 + 10; 3 int T[maxn]; //默认排序从小到大 4 int n; 5 /*----------以下为二分检索----------*/ 6 int Binary_Search(int x){ 7 int pos=0; 8 int l=1,r=n; 9 while(l<=r){ 10 int mid=(l+r)>>1; 11 if(T[mid]==x){ 12 pos=mid; 13 break; 14 } 15 if(T[mid]<x)l=mid+1; 16 else r=mid-1; 17 } 18 return pos; 19 } 20 /*----------以上为二分检索----------*/ 21 int main(){ 22 scanf("%d",&n); 23 for(int i=1;i<=n;++i)scanf("%d",&T[i]); 24 int x; 25 scanf("%d",&x); 26 printf("下标j=%d ",Binary_Search(x)); 27 }
4. 分析
顺序检索:O(n)
二分检索:O(logn)
5. 源码
顺序检索: https://github.com/JayShao-Xie/algorithm-work/blob/master/InOrderToFind.cpp
二分检索: https://github.com/JayShao-Xie/algorithm-work/blob/master/Binary_Search.cpp