Home / Questions / Write a Java program to sort each row of the following 2D array in ascending order. Example Input: 9 7 5 3 1 2 6 4 8 Expected Output: 5 7 9 1 2 3 4 6 8
Explanatory Question

Write a Java program to sort each row of the following 2D array in ascending order.

Example Input:


9 7 5  
3 1 2  
6 4 8  

Expected Output:


5 7 9  
1 2 3  
4 6 8  

👁 51 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Here is the Java program to sort each row of a 2D array in ascending order:


import java.util.Arrays;

public class RowWiseSorting {
    public static void main(String[] args) {
        int[][] array = {
            {9, 7, 5},
            {3, 1, 2},
            {6, 4, 8}
        };

        System.out.println("Original 2D Array:");
        print2DArray(array);

        // Sorting each row of the 2D array
        for (int i = 0; i < array.length; i++) {
            Arrays.sort(array[i]); // Sorts each row in ascending order
        }

        System.out.println("\n2D Array After Row-wise Sorting:");
        print2DArray(array);
    }

    // Method to print a 2D array
    public static void print2DArray(int[][] array) {
        for (int[] row : array) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Output:


Original 2D Array:  
[9, 7, 5]  
[3, 1, 2]  
[6, 4, 8]  

2D Array After Row-wise Sorting:  
[5, 7, 9]  
[1, 2, 3]  
[4, 6, 8]