学习笔记:二分法查找的递归和非递归两种算法

首先是非递归查找函数:

 1 int BinarySearch(PTABLE table,int numb){
 2     int Left,Right,Mid,ERROR=-1;
 3     Left=0;
 4     right=table->Lenth-1;
 5     while(right>=Left){
 6         mid=(Right+Left)/2;
 7         if(table->data[mid]>numb)
 8             Right=mid-1;
 9         else if(table->data[mid]<numb)
10             Left=mid-1;
11         else
12             return(table->data[mid]);
13     }
14     return(ERROR);
15 }

采用递归方式:

 1 //recurbinary
 2 int recurbinary(PTABLE table,int Left,int Right,int numb){
 3     if(Left>Right)
 4         return(-1);
 5     mid=(Left+Right)/2;
 6     if(mid==table->data[mid])
 7         return(table->data[mid]);
 8     else if(mid>table->data[mid])
 9         recurbinary(table,Left,mid-1,numb);
10     else if(mid<table->data[mid])
11         recurbinary(table,mid+1,Right,numb);
12 }

 

posted @ 2016-09-13 18:43  Madao东治  阅读(3380)  评论(0编辑  收藏  举报