• 递归练习





    1
    import java.io.IOException; 2 3 public class Digui1 { 4 5 public static void main(String[] args) { 6 // TODO Auto-generated method stub 7 Digui1 d= new Digui1(); 8 try { 9 d.printInput(); 10 } catch (IOException e) { 11 e.printStackTrace(); 12 } 13 } 14 15 private void printInput() throws IOException { 16 char i = (char) System.in.read(); 17 if (i != '#') { 18 printInput(); 19 } 20 if (i != '#') { 21 System.out.print(i); 22 } 23 } 24 25 }

     1 import java.io.IOException;
     2 
     3 public class Digui1 {
     4 
     5     int a[] = {1,1,2,3,5,8,13,21,34,55,88};
     6     int low = 0;
     7     int high = 10;
     8     int mid = (low+high)/2;
     9     public static void main(String[] args) {
    10         Digui1  d= new Digui1();
    11         d.search(34);
    12     }
    13     
    14     private void search(int key)  {
    15         
    16         if(a[mid] < key) {
    17             low = mid+1;
    18             mid = (low+high)/2;
    19             search(key);
    20         }
    21         else if(a[mid] > key) {
    22             high = mid-1;
    23             mid = (low+high)/2;
    24             search(key);
    25         }
    26         else{
    27             System.out.print(mid);
    28         }
    29     }
    30 }

    折半查找法:输出8

    汉诺塔问题:

     1 public class Digui1 {
     2     static int step;
     3     static int p;
     4     public static void main(String[] args) {
     5         Digui1  d= new Digui1();
     6         d.move(4,'x','y','z');
     7         System.out.println("step:"+step);
     8         System.out.println(p);
     9     }
    10     //将n个盘子借助y从x移到z
    11     private void move(int n,char x,char y, char z)  {
    12         p++;
    13         if(n == 1) {
    14             System.out.println(x+"→"+z);
    15             step++;
    16         }else{
    17             move(n-1,x,z,y);//将n-1个盘子借助z从x移到y
    18             System.out.println(x+"→"+z);
    19             step++;
    20             move(n-1,y,x,z);//将n-1个盘子借助x从y移到z
    21         }        
    22     }
    23 }
     1 x→y
     2 x→z
     3 y→z
     4 x→y
     5 z→x
     6 z→y
     7 x→y
     8 x→z
     9 y→z
    10 y→x
    11 z→x
    12 y→z
    13 x→y
    14 x→z
    15 y→z
    16 step:15
    17 15

     目标:将n个盘子从x借助y移动到z

    步骤:

    1、将n-1个盘子从x借助z移动到y;

    2、将第n个盘子从x移动到z上

    3、将n-1个盘子从y借助x移动到z。

  • 相关阅读:
    C# 保存base64格式图片
    C# 日期比较
    Socket的使用
    地质演变完整事记
    计算机实用的使用技巧
    ebook 电子书项目
    ppt演讲者模式
    IT行业三大定律
    史前生命
    Oracle DataGuard发生归档丢失增量备份恢复备库
  • 原文地址:https://www.cnblogs.com/hixin/p/4136412.html
Copyright © 2020-2023  润新知