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);
}
}
Theory:
Matrix
Matrix is a array which is rectangular. In this we store elements in the row and column form.
Solution:
Algorithm:
1. Start
2. Create class Search2D
3. write method search for searching
4. set index top right element
5. use while loop for searching till i<4 and j>=0
6. By using if condition check if the index element and desired element are equal then display element is found else display element is not found.
7. In main method create matrix also create class objects.
8.by using class objects call the search() method and pass matrix and search element.
9.end
Code:
class Search2D {
private void search(int[][] matrix, int desiredItem)
{
int i = 0, j = 4; // set indexes for top right element
System.out.println("\nSearching for " + desiredItem);
while (i < 4 && j >= 0) {
if (matrix[i][j] == desiredItem) {
System.out.print("Found at " + i + " " + j+"\n");
return;
}
if (matrix[i][j] > desiredItem)
j--;
else // if mat[i][j] < x
i++;
}
System.out.print("Element not found\n");
}
// 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("\n***These should be successful searches: ***");
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*** These should be unsuccessful searches: ***");
search2D.search(matrix,28);
search2D.search(matrix,5);
search2D.search(matrix,12);
}
}
Output: