二分查找法BinarySearch

二分查找法的两种形式-递归和非递归,递归形式简单,但是在数量大时所消耗的时间空间也极大,下面以Java代码给出两种形式的具体实现
1)非递归

public class BinarySearch{
       public static void main(String[] args){
       //有时间补上传入浮点数异常的情况
       }
       //-1代表未成功查找
       public static int search(int key,int[] a){
                if(a.length<=0){
                       return  -1;  
                }
                else
                {
                       int start = 0;
                       int end = a.length-1;
                       while(start<=end){
                             mid = (start + end)/2;
                             if(a[mid]==key)
                                   return mid;
                             else if(a[mid]>key)
                                   end = mid-1;
                             else
                                   start = mid+1;
                        }
                        return -1;
                 }
       }
} 

2)递归

public class BinarySearch{
       public static void main(String[] args){
       int[]  a  = {1,2,3,4,5}
       start = 0;
       end = a.length - 1;
       k = 8;
       search(k,a,start,end);
       //有时间补上传入浮点数异常的情况
      
       }
       //-1代表未成功查找
       public static int search(int key,int[] a,int start,int end){
                if(start > end){
                       return  -1;  
                }
                else
                {
                       int mid = (start+end)/2;
                       if(a[mid]==key)
                            return mid; 
                        else if(a[mid]>key)
                              search(key,a,start,mid-1)
                        else if(a[mid]<key)
                              search(key,a,mid+1,end)           
                 }
        }
} 

2018-01-28

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容