javabinary-searchintellij-15

Binary search in sorted matrix


I was trying to implement the test case in IntelliJ; However, the output result was "[I@65b54208", I don't understand why this is my result, how to show my result as an integer in the matrix?

public class SearchMatrix {
    public static void main(String[] args) {
        int matrix[][]={{0,1,3},{4,5,6},{7,8,9}};
        SearchMatrix s = new SearchMatrix();
        System.out.println(s.Binary(matrix,3));
    }
    public int[] Binary(int[][] matrix, int target){
        int r= matrix.length;
        int c= matrix[0].length;
        int left=0;
        int right=r*c-1;
        while (left<=right){
            int mid=left+(right-left)/2;
            int row=mid/c;
            int col=mid%c;
            if (matrix[row][col]<target){
                left= mid+1;
            } else if (matrix[row][col]>target){
                right= mid-1;
            } else{
                return new int[] {row,col};
            }
        }
        return new int[] {-1,-1};
    }
}

Solution

  • You can't just print array as a primitive variable. Printing the array will just output the hash code of the array (not the content you wish for). Either print each element by separate statements

    int[] result = s.Binary(matrix,3);
    
    System.out.println(result[0]);
    System.out.println(result[1]);
    

    Or use a built in function for printing contents of array from java.util.Arrays package javadoc

     System.out.println(Arrays.toString(s.Binary(matrix, 3)));