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
Single Choice
Views 43
Answer:
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]
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.