zoukankan      html  css  js  c++  java
  • 信手胡写二分法

    /**
     * 几个二分法
     * 使用二分法的前提是数组已经排好序
     * 
     * @author tiger
     */
    public class erfenfa {
    
     /**
      * 中间调用多个自身方法
      */
     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 erfenfa().erFenFa(tiger, 0, 7, 2);
      System.out.println("方法二:");
      new erfenfa().erFenFa2(tiger, 0, 7, 2);
      System.out.println("方法三:");
      new erfenfa().erFenFa3(tiger, 0, 7, 2);
     }
    }
    
    /*打印结果如下:
     方法一:
     2在数组中的索引是:3
     方法二:
     2在数组中的索引是:3
     2在数组中的索引是:6
     2在数组中的索引是:1
     2在数组中的索引是:2
     方法三:
     2在数组中的索引是:3
    */
  • 相关阅读:
    mysql5.5的安装与配置(亲测版)
    CentOS 6.5升级Python和安装IPython(亲测可用)
    运维mysql基础
    linux命令巧用,随手记
    《大话设计模式》——建造者模式
    《大话设计模式》——外观模式
    《大话设计模式》——模版方法模式
    抽象类和接口的区别
    《大话设计模式》——原型模式
    《大话设计模式》——工厂方法模式
  • 原文地址:https://www.cnblogs.com/chaohi/p/2330336.html
Copyright © 2011-2022 走看看