我应该如何递归地为矩形实现binarySearch?

时间:2017-02-01 05:14:41

标签: java recursion

我正在为矩形递归地编写binarySearch方法。 我的矩形类工作正常 这是它:

    public class Rectangle implements Comparable<Rectangle> {
    private int length;
    private int width;
        private int perimeter;


    public Rectangle(int l, int w){
        this.length = l;
        this.width = w;
    } 

    public  int getLength() {
        return length;
    }

    public  int getWidth(){
        return width;
    }

        public void setLength(int l){
            length= l;
        }
        public void setWidth(int w){
            width = w;
        }

    public int getPerimeter(){
               perimeter = 2*(length+width);

               return perimeter;
    }




        @Override
    public int compareTo(Rectangle other){
               return Double.compare(this.getPerimeter(), other.getPerimeter());
        }

        @Override
        public String toString(){
            return "Rectangle: "+ width +" by "+ length ;
        }
}

但问题出在我的binarySearch方法上 在主要方法中,我无法打印出实际的矩形。我不知道这个方法本身是错的还是我在打印中写的方式?

import java.util.Arrays;

public class Problem2{

    public static <AnyType extends Comparable<AnyType>>       
     int binarySearch(AnyType[] a, AnyType x){
        return binarySearch(a, x, 0, a.length-1);
     }

    public static <AnyType extends Comparable<AnyType>> int binarySearch
      (AnyType[] a, AnyType x, int start, int stop){
        if(start < stop)
            {
                int mid = (stop + start) / 2;
                if(x.compareTo(a[mid]) == -1)
                    return binarySearch(a, x, start, mid);
                else if(x.compareTo(a[mid]) == 1)
                    return binarySearch(a, x, mid+1, stop);
                else
                    return mid;
            }
        return -1;
    }

      public static void main(String []args){

            Rectangle[] arr = { new Rectangle(2,6), new Rectangle(4,7), new Rectangle(3,9),
                                new Rectangle(1,2), new Rectangle(2,4), new Rectangle(7,7)}; 


            for(Rectangle rec: arr){
            System.out.println("the list is " + rec);
            }

          System.out.println(binarySearch(arr,arr[5]));

      }
}

所以基本上如果你运行这个,上面的部分工作正常。最后一个打印输出不给我矩形。它打印出数字。就像它是arr [1]然后它打印1,但如果它是5然后它给-1。

1 个答案:

答案 0 :(得分:0)

您的binarySearch方法会在找到矩形的数组中返回 index ,而不是矩形本身。

你想要这样的东西:

int index = binarySearch(arr,arr[5]);
if (index != -1)
    System.out.println(arr[index]);
else
    System.out.println("Rectangle not found");