Using the following code answer this: public static void main(String[] args) { i
ID: 3764227 • Letter: U
Question
Using the following code answer this:
public static void main(String[]
args) {
int[][] m1 = {
{ 14, 11, 13, 12 },
{ 18, 15, 13, 13 },
{ 19, 16, 15, 17 } };
int[][] m2 = {
{ 54, 53, 51, 52 },
{ 51, 59, 52, 56 },
{ 53, 54, 52, 58 } };
System.out.println("First array:");
displayArray(m1);
System.out.println("Second array:");
displayArray(m2);
/*
write simple code to test your method
and use
displayArray to display the result if applicable
*/
}
//write your methods code here.
public static void
displayArray(int[][] m) {
for (int
r
= 0;
r
< m.length;
r
++) {
for (int
c
= 0;
c
< m[
r
].length;
c
++)
System.
out
.print(m[
r
][
c
] + " ");
System.
out
.println();
}
}
}
Explanation / Answer
Code :
public class Test
{
public static void main(String[]args)
{
int[][] m1 = {
{ 14, 11, 13, 12 },
{ 18, 15, 13, 13 },
{ 19, 16, 15, 17 } };
int[][] m2 = {
{ 54, 53, 51, 52 },
{ 51, 59, 52, 56 },
{ 53, 54, 52, 58 } };
System.out.println("First array:");
displayArray(m1);
System.out.println("Second array:");
displayArray(m2);
System.out.println("First array after sorting each rows :");
int[][] m3=sortRow(m1);
displayArray(m3);
}
// FUNCTION TO SORT THE ROWS OF ARRAYS
public static int[][] sortRow(int[][] m)
{
int[][] sum = new int[m.length][m[0].length];
for (int li = 0; li < m.length; li++)
for (int lj = 0; lj < m[0].length; lj++)
sum[li][lj] = m[li][lj];
int temp = 0;
for(int row = 0; row < sum.length ; row++)
{
for(int col = 0; col < sum[row].length; col++){
for(int nextCol = col; nextCol < sum[row].length; nextCol++) {
if(sum[row][col] > sum[row][nextCol])
{
temp = sum[row][col];
sum[row][col] = sum[row][nextCol];
sum[row][nextCol] = temp;
}
}
}
}
return sum;
}
public static void displayArray(int[][] m)
{
for (int r= 0;r< m.length;r++)
{
for (int c= 0;c< m[r].length;c++)
System.out.print(m[r][c] + " ");
System.out.println();
}
}
}
Result :
First array:
14 11 13 12
18 15 13 13
19 16 15 17
Second array:
54 53 51 52
51 59 52 56
53 54 52 58
First array after sorting each rows :
11 12 13 14
13 13 15 18
15 16 17 19
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.