Java

How to Sort 2d Array in Java

A two-dimensional or 2D array is a collection of columns and rows. Programmers can randomly access the 2D array elements or each cell individually by utilizing their indexes. With the help of sorting, array elements are arranged according to the requirements, whether in ascending or descending order. More specifically, the Java “Array.sort()” can be utilized for the elements of a 2D array within a program.

This tutorial will discuss how to sort 2D arrays in Java.

How to Sort 2D Array in Java?

In Java, you can sort a 2D array using:

We will now discuss each of the mentioned methods one by one.

Method 1: Row-wise sorting of 2D Array in Java

In row-wise sorting, you can utilize the “Array.sort()” method to sort the array elements. It iterates each element of a specific row and swaps the integers when the current element is greater than the next.

Let’s check out an example to understand the implementation side.

Example
In this example, first we will create a static method “rowWiseSorting()” to sort the array in ascending order by calling “Arrays.sort()” method of the Arrays class and then print the sorted elements of array using “for” loops:

static int rowWiseSorting(int arr[][]) {
for (int i = 0; i < arr.length; i++) {
          Arrays.sort(arr[i]);
    }
for (int i = 0; i < arr.length; i++) {
     for (int j = 0; j < arr[i].length; j++) {
       System.out.print(arr[i][j] + " ");
     }
     System.out.println();
   }
    return 0;
}

Here, we have a 2D array named “arr” of 3×3 matrix form (three rows and three columns). Now, to sort the rows of the created array, we will call the method “rowWiseSorting()” by passing array as an argument in the main() method:

public static void main(String[] args) {
    int arr[][] = new int [][]{
         {12, 14, 4},
            {14, 23, 20},
            {28, 25, 8},
            {11, 5, 1}};
    rowWiseSorting(arr);
    }
}

As you can see, we have sorted our array in ascending order:

Want to try out column-wise sorting in Java? Have a look at the following section.

Method 2: Column-wise sorting of 2D Array in Java

To column-wise sort a 2D Array in Java, call the “Arrays.sort()” method with a “Comparator interface”. A Comparator interface defines a “compare()” method that accepts two parameters and then compares them with each other. If the passed parameters are equal, it returns zero. If the 1st parameter is greater than the 2nd parameter, it returns a positive value. If not, a negative value is returned.

Example
In this example, we will create a method named “columnWiseSorting()” with two arguments, a 2D array “arr[][]” and a column number named “colmn”. Then, call the “Arrays.sort()” method with the “Comparator interface” to compare the values of a column. Finally, we will print the values of the sorted column of array using “for” loops:

static void columnWiseSorting(int arr[][], int colmn) {
        Arrays.sort(arr, new Comparator<int[]>() {
                    public int compare(int[] frst, int[] scnd) {
                          if(frst[colmn-1] > scnd[colmn-1]) {
                                 return 1;
                           }
                          else return -1;
                           }
                          });
}
    for(int i = 0; i< arr.length; i++) {
      for (int j = 0; j < arr[i].length; j++) {
        System.out.print(arr[i][j] + " ");
    }
       System.out.println();
}

We will utilize the already created array named “arr” and pass it to the “columnWiseSorting()” as first parameter and “1” as the second parameter:

columnWiseSorting(arr,1);

Execution of the above-given program will sort the first column of our 2D array:

We compile all the essential information to sort the 2D array in Java.

Conclusion

In Java, a 2D array can be sorted row-wise or column-wise as per requirements. For row-wise sorting, only the Array.sort() method is utilized; however, in column-wise sorting, the Array.sort() method is called with the Comparator interface. For row-wise sorting, no parameter is passed to Array.sort() method, whereas, in the column-wise sorting method, the number of columns that need to be sorted is mentioned as a parameter. This tutorial discussed the methods to sort the 2D array in Java with examples.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.