Problem Statement: Implement a function
int[][] Sort2DArraysByRow(int m,int n,int arr[][])
The function accepts a two-dimensional integer array ‘arr’ of ‘m’ rows and ‘n’ columns . Implement the function to return 2D array after sorting each row of array ‘arr’ in ascending array.
Assumption:
1. m>0 and n>0
2. Array index starts from (0,0).
Note: You need to sort each row in ascending order.
Example:
Input:
3
4
7 9 2 4
3 2 5 4
9 7 8 1
Output:
2 4 7 9
2 3 4 5
1 7 8 9
import java.io.*; class Sort2DMatrix { static int[][] Sort2DArraysByRow(int m,int n,int arr[][]) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n - j - 1; k++) { if (arr[i][k] > arr[i][k + 1]) { int t = arr[i][k]; arr[i][k] = arr[i][k + 1]; arr[i][k + 1] = t; } } } } return arr; } public static void main(String args[]) { int m=3,n=4; int arr[][] = { { 7,9,2,4 },{ 3,2,5,4 },{ 9,7,8,1 } }; int[][] ar=new int[m][n]; ar=Sort2DArraysByRow(m,n,arr); for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) System.out.print(ar[i][j] + " "); System.out.println(); } } } /* OUTPUT 2 4 7 9 2 3 4 5 1 7 8 9 */
Request:-If you found this post helpful then let me know by your comment and share it with your friend.
0 Comments