zoukankan      html  css  js  c++  java
  • 二分查找(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);
           }
       }
    }
  • 相关阅读:
    js中 offset /client /scroll总结
    python的安装和环境配置
    git详解
    Xmind
    Linux 文件搜索命令
    Linux 文件和目录命令
    Linux 系统关机重启命令
    Linux系统信息命令
    Day07
    ModuleNotFoundError: No module named 'pysqlite2'
  • 原文地址:https://www.cnblogs.com/felixzh/p/4730355.html
Copyright © 2011-2022 走看看