zoukankan      html  css  js  c++  java
  • 几个二分法示例

    /**
     * 几个二分法
     * @author tiger
     */
    public class Test {

     /**
      * 中间调用多个自身方法
      */
     public void erFenFa(int[] array, int fromIndex, int toIndex, int goal){
      if(fromIndex > toIndex){ // 这一句非常重要!
       return;
      }
      int middle = (fromIndex + toIndex) / 2;
      if(array[middle] == goal){
       System.out.println(goal + "在数组中的索引是:" + middle);
       return;
      }else if(array[middle] < goal){
       erFenFa(array, middle+1, toIndex, goal);
      }else{
       erFenFa(array, fromIndex, middle-1, goal);
      }
     }
     
     /**
      * 中间调用多个自身方法
      * 将能打印出所有目标值所在索引
      *
      * 这其实和二叉树的遍历非常相像!!!
      * 这个方法的算法复杂度其实和线性的遍历一模一样!!!
      */
     public void erFenFa2(int[] array, int fromIndex, int toIndex, int goal){
      if(fromIndex > toIndex){ // 这一句非常重要!
       return;
      }
      int middle = (fromIndex + toIndex) / 2;
      if(array[middle] == goal){
       System.out.println(goal + "在数组中的索引是:" + middle);
      }
      erFenFa2(array, middle+1, toIndex, goal);
      erFenFa2(array, fromIndex, middle-1, goal);
     }
     
     
     /**
      * 一个循环搞定
      * 用循环的方法来实现二分法,似乎没有办法能够打印出所有的目标索引!
      * 试想下,假如数组中所有元素都是目标值,那怎么打印出所有呢??
      */
     public void erFenFa3(int[] array, int fromIndex, int toIndex, int goal){
      int middle = 0;
      while(fromIndex < toIndex)
      {
       middle = (fromIndex + toIndex) / 2;
       if(array[middle] == goal){
        System.out.println(goal + "在数组中的索引是:" + middle);
        return; //此句非常重要,如果没有,当数组中有目标值,程序能执行到这里时,
          //由于不会对fromIndex和toIndex造成变化,将会陷入死循环!!!
       }else if(array[middle] < goal){
        fromIndex = middle + 1;
       }else{
        toIndex = middle -1;
       }
      }
     }
     
     
     /**
      * 程序入口
      * @param args
      */
     public static void main(String[] args) {
      int[] tiger = {1,2,2,2,5,6,2,8};
      System.out.println("方法一:");
      new Test().erFenFa(tiger, 0, 7, 2);
      System.out.println("方法二:");
      new Test().erFenFa2(tiger, 0, 7, 2);
      System.out.println("方法三:");
      new Test().erFenFa3(tiger, 0, 7, 2);
     }
    }

    /*打印结果如下:
    方法一:
    2在数组中的索引是:3
    方法二:
    2在数组中的索引是:3
    2在数组中的索引是:6
    2在数组中的索引是:1
    2在数组中的索引是:2
    方法三:
    2在数组中的索引是:3*/

  • 相关阅读:
    const对象 不能调用非const修饰的成员函数
    Sqlserver 查询 临时字段
    win7 VC6.0 安装 fatal error C1083: Cannot open include file: 'Iphlpapi.h': No such file or directory
    RtlWerpReportException failed with status code :-1073741823
    MFC 去掉CWnd的边框
    阿里云 linux 找回mysql root密码
    IE 内使用ActiveX,写注册表被重定向到如下注册表
    mysqli得到记录数量
    error C4996 The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name
    在MFC主对话框OnInitDialog()中弹出对话框
  • 原文地址:https://www.cnblogs.com/chaohi/p/2330345.html
Copyright © 2011-2022 走看看