2d Array Sorting in JavaAn array of arrays can be a twodimensional 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 onedimensional arrays, because the elements of 2D arrays can be accessed at random. Within a twodimensional 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
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 columnwise 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 Rowwise approach. Approach: Using Columnwise MethodAn 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 Columnwise sorting approach is O(N^{3}). Approach: Using Rowwise MethodAn 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 rowwise sorting approach is O(N*M*M) which simplifies into O(N^{2}) as M is constant in this case where N represents the length of the array.
Next TopicAliquot Sequence in Java
