1、线性查找

在数组a[]={0,1,2,3,4,5,6,7,8,9,10}中查找1这个元素。

 

(1)普通搜索方法,一个循环从0到10搜索,这里略。

 

(2)递归(从中间向两边)

 1 //递归一定要写成记忆化递归 
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 bool vis[11];
 5 int count1=0;
 6 
 7 void search(int n){
 8     count1++;
 9     if(n>10||n<0||vis[n]){
10         //cout<<"back"<<endl;
11     }
12     else if(n==1){
13         vis[n]=true;
14         cout<<"find"<<endl;
15     } 
16     else {
17         vis[n]=true;
18         search(n-1);
19         search(n+1);
20         
21     }
22 }
23 
24 int main(){
25     int a[]={0,1,2,3,4,5,6,7,8,9,10};
26     search(9);
27     cout<<count1<<endl;
28     return 0;
29 
30 } 
递归(从中间到两边)

相关文章:

  • 2021-07-27
  • 2022-02-27
  • 2022-12-23
  • 2022-12-23
  • 2021-03-30
  • 2021-08-06
猜你喜欢
  • 2022-12-23
  • 2022-01-07
  • 2021-12-15
  • 2021-12-30
  • 2022-12-23
  • 2021-12-31
  • 2021-12-10
相关资源
相似解决方案