2d Array Sorting in Java

An array of arrays can be a two-dimensional array. The 2D array is composed of matrices that show a set of rows and columns. We can access individual cells in a 2D array using their indices, just like we can with one-dimensional arrays, because the elements of 2D arrays can be accessed at random.

Within a two-dimensional array, each cell possesses two indexes: the row number and the column number. One way to arrange elements in a 2D array in a certain order is to sort them. Either ascending or descending order can be used for the 2D array. Here are some methods for sorting a 2D array in Java in both ascending and descending order.

There are mainly 2 approaches. They are as follows

  1. Using Column-wise Method
  2. Using Row-wise Method

Example 1:

Input:

The array before sorting is:

{ 11, 39, 27, 42 },

{ 10, 90, 93, 91 },

{ 56, 89, 54, 78 },

{ 20, 65, 24, 64 }

Output:

The array after sorting is:

{ 10, 39, 24, 42 },

{ 11, 65, 27, 64 },

{ 20, 89, 54, 78 },

{ 56, 90, 93, 91 }

Explanation:

Here, the 2D dimensional array is sorted by using the column-wise approach.

Example 2:

Input:

The array before sorting is:

{ 11, 39, 27, 42 },

{ 10, 90, 93, 91 },

{ 56, 89, 54, 78 },

{ 20, 65, 24, 64 }

Output:

The array after sorting is:

{ 11, 27, 39, 42},

{ 10, 90, 91, 93},

{ 54, 56, 78, 89},

{ 20, 24, 64, 65}

Explanation:

Here, the 2D dimensional array is sorted by using the Row-wise approach.

Approach: Using Column-wise Method

An example of sorting a 2D array in Java so that all of its elements are arranged according to columns.

Implementation:

FileName: ColumnMethod.java

Output:

The Array Before Sorting is given by : 
11 39 27 42 
10 90 93 91 
56 89 54 78 
20 65 24 64 
The Array After Sorting is given by : 
10 39 24 42 
11 65 27 64 
20 89 54 78 
56 90 93 91

Complexity Analysis:

The time complexity for Column-wise sorting approach is O(N3).

Approach: Using Row-wise Method

An example of sorting a 2D array's elements all the way by row.

Implementation:

FileName: RowMethod.java

Output:

The Array Before Sorting is given by : 
11 39 27 42 
10 90 93 91 
56 89 54 78 
20 65 24 64 
The Array After Sorting is given by : 
11 27 39 42 
10 90 91 93 
54 56 78 89 
20 24 64 65

Complexity Analysis:

Generally, the time complexity for row-wise sorting approach is O(N*M*M) which simplifies into O(N2) as M is constant in this case where N represents the length of the array.