In this tutorial, we will learn how to sort a 2D array in Java. As we know, a 2D array consists of rows and columns, thus we can sort the 2D array column-wise or row-wise, we will see both the programs.
1. Sorting 2D Array Column-wise
In the following program, we are sorting the given 2D array column-wise, this means that each column of the array needs to be sorted individually.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 2D Array
int[][] array = {
{5, 2, 9},
{1, 3, 7},
{4, 0, 8}
};
// Displaying the elements of original array
System.out.println("Original array:");
print2DArray(array);
// Sort each column of 2D Array
sortColumns(array);
// Displaying the elements of sorted array
System.out.println("\nArray sorted column-wise:");
print2DArray(array);
}
// Method to sort each column of the 2D array
public static void sortColumns(int[][] array) {
int numRows = array.length;
int numCols = array[0].length;
for (int col = 0; col < numCols; col++) {
// Extract the column into a temporary array
int[] columnArray = new int[numRows];
for (int row = 0; row < numRows; row++) {
columnArray[row] = array[row][col];
}
// Sort the temporary array
Arrays.sort(columnArray);
// Write the sorted values back into the column
for (int row = 0; row < numRows; row++) {
array[row][col] = columnArray[row];
}
}
}
// This method prints the 2D array
public static void print2DArray(int[][] array) {
for (int[] row : array) {
System.out.println(Arrays.toString(row));
}
}
}
Output:
Original array:
[5, 2, 9]
[1, 3, 7]
[4, 0, 8]
Array sorted column-wise:
[1, 0, 7]
[4, 2, 8]
[5, 3, 9]
2. Sorting 2D Array Row-wise
In the following program, we are sorting the given 2D array row-wise, this means that each row of the array needs to be sorted individually.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// 2D Array
int[][] array = {
{5, 2, 9},
{1, 3, 7},
{4, 0, 8}
};
// Displaying the elements of original array
System.out.println("Original array:");
print2DArray(array);
// Sort each row of 2D Array
sortRows(array);
// Displaying the elements of sorted array
System.out.println("\nArray sorted row-wise:");
print2DArray(array);
}
// Method to sort each row of the 2D array
public static void sortRows(int[][] array) {
for (int[] row : array) {
Arrays.sort(row);
}
}
// This method prints the 2D Array
public static void print2DArray(int[][] array) {
for (int[] row : array) {
System.out.println(Arrays.toString(row));
}
}
}
Output:
Original array:
[5, 2, 9]
[1, 3, 7]
[4, 0, 8]
Array sorted row-wise:
[2, 5, 9]
[1, 3, 7]
[0, 4, 8]
Leave a Reply