Home  >  Article  >  Java  >  Sort 2D array based on values ​​in any given column in Java

Sort 2D array based on values ​​in any given column in Java

WBOY
WBOYforward
2023-08-29 21:01:03948browse

An array is a linear data structure used to store a set of elements with similar data types. It stores data in a sequential manner. Once we create an array, we cannot change its size, i.e. it is fixed length.

Suppose we have a two-dimensional array of order M x M, where M is the number of rows and columns. We have to sort the specified column of the given array. In this article we will try to find the solution to the given problem.

Sort a two-dimensional array based on column values

Sort means rearranging the elements of a given list or array in ascending or descending order. Let us understand what is sorting through the following visual representation -

Example 1

When we sort the first column of the two-dimensional array -

Sort 2D array based on values ​​in any given column in Java

Syntax of two-dimensional array

// declaration with size
Data_Type nameOfarray[][] = new Data_Type[sizeofrow][sizeofcolumn]; 
Or,
// declaration and initialization
Data_Type nameOfarray[][] = { {values separated by comma} }; 

We can use any of the above syntax in our program.

In place of Data_Type, we can give primitive data types such as int and double. Row and Column are the desired array sizes.

Before entering the program, let us discuss one more thing.

Comparator interface

Java provides a built-in method called sort() to sort arrays and collections in natural order. Comparator is a general interface that we can use when we need to sort elements in a custom way. Basically, we can control the order of sorting. This interface defines a method 'compare()', which accepts two parameters and compares them. Returns 0 when the two arguments are equal, a positive value if the first argument is greater than the second argument, and a negative value otherwise.

grammar

Comparator<typeOfelement> nameOfcollection = new Comaprator<typeOfelement>() {
   // your code here
};

algorithm

  • Step 1 - Define method "araySort()" along with two parameters in class "Srt". In this method, create an object of Comparator interface "comp". Now, define the comparison method that takes both arrays of rows together as parameters.

  • Step 2 - Further, we will use if-else block to compare the specified column values, if the element of the first column is greater than the second column, then return 1, otherwise return - 1 .

  • Step 3 - Now, sort the array using “Arrays.sort()” method.

  • Step 4 - Use two for loops to print the new sorted array.

  • Step 5 - Finally, in the main() method, we will declare and initialize an array. Continue to create an object of class "Srt" and call the method "araySort()" with "aray" and column index as parameters.

Example

import java.util.*;
class Srt {
   void araySort(int aray[][], int cl) {
      Comparator<int[]> comp = new Comparator<int[]>() {
         public int compare(int[] val1, int[] val2) {
            if(val1[cl-1] > val2[cl-1]) {
               return 1;
            } else {
               return -1;
            }
         }
      };
      Arrays.sort(aray, comp);
      System.out.println("The sorted array: ");
      for(int i = 0; i< aray.length; i++) {
         for (int j = 0; j < aray[i].length; j++) {
            System.out.print(aray[i][j] + " ");
         }
         System.out.println();
      }
   }
}
public class Sorting {
   public static void main(String[] args) {
      int aray[][] = { { 7, 2, 1, 3 }, { 6, 1, 3, 7 }, { 4, 9, 8, 0 }, { 8, 0, 1, 2 } };
      System.out.println("The given array we have: ");
      // for each loop to print original 2D array
      for (int[] array : aray) {
         for (int print : array) {
            System.out.print(print + " ");
         } 
         System.out.println();
      }
      Srt obj = new Srt();
      // calling method using object
      obj.araySort(aray, 1);
      obj.araySort(aray, 3);
   }
}

Output

The given array we have: 
7 2 1 3 
6 1 3 7 
4 9 8 0 
8 0 1 2 
The sorted array: 
4 9 8 0 
6 1 3 7 
7 2 1 3 
8 0 1 2 
The sorted array: 
8 0 1 2 
7 2 1 3 
6 1 3 7 
4 9 8 0

in conclusion

A two-dimensional array is an array with rows and columns. In this article, we created a Java program to sort a two-dimensional array based on the values ​​of a specified column. We saw how to sort an array or collection using the built-in method "compare()" of the Comparator interface.

The above is the detailed content of Sort 2D array based on values ​​in any given column in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete