In: Computer Science
Trace the sample run provided for Search2D class
..................................................................
public class Search2D
{
/**
* Searches for the desiredItem in a
rectangular matrix[][] where
* elements are sorted within each row and
within each column
* If the element is found, prints its
position,
* otherwise prints "not found"
*
* @author YOUR NAME
* @version 10/20/2020
*
*/
private void search(int[][] matrix, int
desiredItem)
{
// TODO Project 4
// TODO must implement
with one loop only
System.out.println("Searching for " + desiredItem);
}
// driver to test search method
public static void main(String[] args)
{
int matrix[][] = {
{9, 10, 20, 21, 40},
{11, 15, 25, 26, 45},
{13, 27, 29, 30, 48},
{17, 32, 33, 34, 50}};
Search2D search2D = new
Search2D();
System.out.println("\u001B[35m\u001B[1m*** These should be
successful searches: ***\u001B[0m");
for (int r = 0; r <
matrix.length; r++)
{
for (int c = 0; c < matrix[r].length; c++)
{
search2D.search(matrix, matrix[r][c]);
}
}
System.out.println("\n\u001B[35m\u001B[1m*** These should be
unsuccessful searches: ***\u001B[0m");
search2D.search(matrix,28);
search2D.search(matrix,5);
search2D.search(matrix,12);
}
}
public class Search2D
{
/**
* Searches for the desiredItem in a rectangular matrix[][] where
* elements are sorted within each row and within each column
* If the element is found, prints its position,
* otherwise prints "not found"
*
* @author YOUR NAME
* @version 10/20/2020
*
*/
private void search(int[][] matrix, int desiredItem)
{
// TODO Project 4
// TODO must implement with one loop only
System.out.print("Searching for " + desiredItem + " : ");
for(int i=0,j=0;i<matrix.length ; j++) {
if(j == matrix[0].length ) {
i++;
j=0;
}
if(i == matrix.length) {
break;
}
if(matrix[i][j] == desiredItem) {
System.out.println(i + " " + j);
return;
}
}
System.out.println("not found!");
return;
}
// driver to test search method
public static void main(String[] args)
{
int matrix[][] = {
{9, 10, 20, 21, 40},
{11, 15, 25, 26, 45},
{13, 27, 29, 30, 48},
{17, 32, 33, 34, 50}};
Search2D search2D = new Search2D();
for (int r = 0; r < matrix.length; r++)
{
for (int c = 0; c < matrix[r].length; c++)
{
search2D.search(matrix, matrix[r][c]);
}
}
search2D.search(matrix,28);
search2D.search(matrix,5);
search2D.search(matrix,12);
}
}
OUTPUT: