zoukankan      html  css  js  c++  java
  • 二分查找(递归和非递归实现)

    当然前提是:有序数列,这里以升序为例!

    public class binarySearch {
        public static void main(String[] args) {
        
            int arr[]={1,2,3,4,5,6,7,8,9};
            int key=9;
            //int result=binarySearchMethod_noDiGui(arr,key);//非递归实现
            int result=binarySearchMethod_DiGui(arr,0,arr.length-1,key);//递归实现
            System.out.println("结果:"+result);
        }
        
       public static int  binarySearchMethod_noDiGui(int arr[],int key){
           
           int left =0;
           int right=arr.length-1;
           int mid=(left+right)>>1;
           
           while(left<=right){
              if(arr[mid]==key){
                  return mid;
              }else if(arr[mid]>key){
                  right=mid-1;
              }else{
                  left=mid+1;
              }
              mid=(left+right)>>1;
           }
            return -1;
        }
       
       public static int binarySearchMethod_DiGui(int arr[],int left,int right,int key){
           
           int mid=(left+right)>>1;
           
           if(left>right){
               return -1;
           }
           
           if(arr[mid]==key){
               return mid;
           }else if(arr[mid]>key){
               right=mid-1;
               return binarySearchMethod_DiGui(arr,left,right,key);
           }else{
               left=mid+1;
               return binarySearchMethod_DiGui(arr,left,right,key);
           }
       }
    }
  • 相关阅读:
    汇编之EBP的认识。
    【转】PE详解
    迟到的,2016年终总结
    Java 反射
    Java 集合与容器类
    Java 类加载与实例化
    Java 类与对象
    Java 值传递与对象拷贝
    Java 面向对象
    二叉树
  • 原文地址:https://www.cnblogs.com/felixzh/p/4742520.html
Copyright © 2011-2022 走看看