Reputation: 43
i tried to code a divide and conquer algorithm that finds an element in 2d array.
Function prototype:
public boolean searchMatrix(int[][] matrix, int target)
Invoking:
x=searchMatrix(matrix[(rows-1)/2][columns],target);
Error is while invoking this int cannot be converted into int[][]
rows is calculated in the beginning as matrix.length and columns as matrix[0].length
Upvotes: 0
Views: 94
Reputation: 1982
If you want to keep sending in the same array, you could add two parameters to show the length and height:
public boolean searchMatrix(int[][] matrix, int rows, int cols, int target)
and later call it as:
x=searchMatrix(matrix,(rows-1)/2,columns,target);
And the initial call would have the original number of rows and columns.
Edit
If you want to pass different parts of the array, you could have an extra parameter telling the number of rows and columns. Generically, this could be something of use.
x=searchMatrix(matrix, rowStartIndex, noOfRows, columnStartIndex, noOfColumns, target);
Upvotes: 1
Reputation: 10174
I want to pass half of the array
You can create a separate half array from the original matrix
array and pass it to your searchMatrix
method.
int[][] halfMatrix = new int[(rows-1)/2][columns];
for(int i=0;i<(rows-1)/2; i++) {
for(int j=0;j<columns;j++) {
halfMatrix[i][j] = matrix[i][j];
}
}
x=searchMatrix(halfMatrix,target);
If you are trying to employ divide and conquer
tactic, which might not be really fruitful from performance point of view, you can do it the following way:
int[][] halfMatrix = new int[(rows-1)/2][columns];
int[][] secondHalfMatrix = new int[(rows+1)/2][columns];
for(int i=0;i<(rows-1)/2; i++) {
for(int j=0;j<columns;j++) {
if(i<(rows-1)/2)
halfMatrix[i][j] = matrix[i][j];
else
secondHalfMatrix[i-(rows-1)/2][j] = matrix[i][j];
}
}
x=searchMatrix(halfMatrix,target) || searchMatrix(secondHalfMatrix,target);
Upvotes: 1