【问题标题】:Recursive via Binary Search Help(Java)通过二分搜索帮助递归(Java)
【发布时间】:2019-02-02 02:57:50
【问题描述】:

我们被告知使用递归类进行二分搜索。但是,由于我的教授(我寻求帮助时没有详细说明)并且一直在与一位同学一起工作,因此我被困住了,因为递归无法正常工作。我们得出需要 int count 的结论,但我不确定在哪里或如何实现它。 Java 不是我最擅长的语言,因此指南或提示会很有帮助。

            public class Recursive {
            public int BinarySearch(int x[], int target, int low, int high)
            {
               if (low >= high) return -1; 
               int mid = (low + high)/2;
               if (x[mid] > target)
                  return BinarySearch(x, target, low, mid-1); 
               else if (x[mid] < target)
                  return BinarySearch(x, target, mid+1, high); ;
               return mid;
            }
            public int firstNnumber(int n)
            {
               if (n < 1) return 0;
               return firstNnumber(n-1) + n;
            }
            public int firstNnumber2(int n)
            {
               if (n==1) return 1;
               if (n==2) return 3;
               boolean even = (n%2 == 0);
               n /= 2;
               if (even)
               {
                   return 2*firstNnumber2(n) + n*n;
               }
               else
                   return 2*firstNnumber2(n) + (n + 1)*(1+n);
            }
            public int gaussian(int n)
            {
               return  n*(n+1)/2;
            }

            static public void main(String [] args)
            {
               Recursive r = new Recursive();
               System.out.println("By Gussain, Sum of first 100000 integers=" + r.gaussian(10000));
               System.out.println("By recurssion 2,    Sum of first 100000 integers=" + r.firstNnumber2(6)); 
            }


            }       

这是打印出来的,我不明白我的代码有什么问题。

根据 Gussain,前 100000 个整数的总和=50005000 通过递归2,前100000个整数之和=21

【问题讨论】:

    标签: java recursion binary binary-search


    【解决方案1】:

    你用错误的参数调用,尝试调用

    static public void main(String [] args){
      Recursive r = new Recursive();
      System.out.println("By Gussain, Sum of first 100000 integers=" + r.gaussian(10000));
      System.out.println("By recurssion 2,    Sum of first 100000 integers=" + r.firstNnumber2(10000)); 
    }
    
    

    【讨论】:

    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 2015-01-21
    • 2011-07-25
    • 2011-03-24
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多