首页 > 代码库 > 递归1--二分查找

递归1--二分查找

递归1--二分查找

一、心得

递归的时候注意返回值,返回的时候是返回到上一层 

 

二、代码及结果

 1 /*
 2 二分查找:
 3 可写递推和递归
 4 其实这两个都只要把递推式子写出来就好
 5 
 6 查找的数大于mid,left=mid+1
 7 小于mid,right=mid-1
 8 边界条件,等于mid,输出即可 
 9 */ 
10 /*
11 心得:注意返回值,返回的时候是返回到上一层 
12 */
13 #include <iostream>
14 using namespace std;
15 //二分查找递归,设置标签 
16 bool binarySearch1(int a[],int left,int right,int num){//初始left=0,right=length-1 
17     bool flag=false; 
18     int mid=(left+right)/2;
19     //cout<<mid<<endl;
20     //cout<<num<<" "<<a[mid]<<endl;
21     if(left<=right){
22         if(num==a[mid]) {
23             flag=true;
24         }
25         else if(num>a[mid]){
26             //cout<<"right:"<<a[mid+1]<<" "<<a[right]<<endl;
27             flag=binarySearch1(a,mid+1,right,num);
28             
29         }
30         else if(num<a[mid]){
31             //cout<<"left:"<<a[left]<<" "<<a[mid-1]<<endl;
32             flag=binarySearch1(a,left,mid-1,num);    
33         }
34     }
35     return flag;
36 } 
37 
38 //二分查找非递归,不设置标签 
39 /*
40 不设置返回值的时候,有栈可以存值 
41 */
42 bool binarySearch2(int a[],int left,int right,int num){//初始left=0,right=length-1 
43     
44     int mid=(left+right)/2;
45     //cout<<mid<<endl;
46     //cout<<num<<" "<<a[mid]<<endl;
47     if(left<=right){
48         if(num==a[mid]) {
49             return true;
50         }
51         else if(num>a[mid]){
52             //cout<<"right:"<<a[mid+1]<<" "<<a[right]<<endl;
53             binarySearch2(a,mid+1,right,num);
54             
55         }
56         else if(num<a[mid]){
57             //cout<<"left:"<<a[left]<<" "<<a[mid-1]<<endl;
58             binarySearch2(a,left,mid-1,num);    
59         }
60     }
61     else{
62         return false;
63     } 
64 } 
65 
66 
67 //二分查找递推
68 bool binarySearch3(int a[],int left,int right,int num){//初始left=0,right=length-1 
69     while(left<=right){
70         int mid=(left+right)/2;
71         if(num==a[mid]) return true;
72         else if(num>a[mid]) left=mid+1;
73         else if(num<a[mid]) right=mid-1;
74     } 
75     return false;
76 } 
77 
78 int main(){
79     int a[11]={1,2,4,7,8,9,11,15,17,19,20};
80     //bool b=binarySearch1(a,0,10,20);
81     //bool b=binarySearch2(a,0,10,7);
82     bool b=binarySearch3(a,0,10,20);
83     cout<<b<<endl;
84     return 0;
85 } 

 技术分享

递归1--二分查找