微信扫一扫打赏支持

分治1--二分查找

分治1--二分查找

一、心得

 

二、题目和分析

 

三、代码和结果

 

 1 #include <iostream>
 2 using namespace std;
 3 int a[10]={1,2,4,5,7,8,9,10,13,20};
 4 
 5 
 6 //非递归 
 7 int find(int i){
 8     int l=0,r=9;
 9     int mid=(l+r)/2;
10     while(l<=r){
11         mid=(l+r)/2;
12         if(a[mid]==i) return mid;
13         else if(i<a[mid]){
14             r=mid-1;
15             //cout<<"l:"<<l<<" "<<"rr:"<<r<<endl;
16         }
17         else{
18             l=mid+1;
19             //cout<<"ll:"<<l<<" "<<"r:"<<r<<endl;
20         }
21     }
22     return -1;
23 }
24 //递归
25 int find_recusion(int i,int l,int r){
26     if(l<=r){
27         int mid=(l+r)/2;
28         if(a[mid]==i) return mid;
29         else if(i<a[mid]){
30             find_recusion(i,l,mid-1);
31         }
32         else{
33             find_recusion(i,mid+1,r);
34         }
35         
36     }
37     else{
38         return -1;
39     } 
40     
41     
42 } 
43 
44 
45 int main(){
46     
47     cout<<find(20)<<endl;
48     cout<<find_recusion(20,0,9)<<endl;
49     cout<<find(3)<<endl;
50     cout<<find_recusion(3,0,9)<<endl;
51     cout<<find(2)<<endl;
52     cout<<find_recusion(2,0,9)<<endl;
53     return 0;
54 } 

posted @ 2017-07-08 06:22  范仁义  阅读(514)  评论(0编辑  收藏  举报