VOOZH about

URL: https://www.geeksforgeeks.org/java/sorting-2d-array-according-values-given-column-java/

⇱ Sorting a 2D Array according to values in any given column in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorting a 2D Array according to values in any given column in Java

Last Updated : 22 Oct, 2024

We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Our task is to sort the 2D array according to values in Column K.

Examples:

Input: If our 2D array is given as (Order 4X4)
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65

Sorting it by values in column 3

Output:

39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90

Java Program to Sort a 2D Array according to values in any given Column


Output
39 27 11 42 
24 64 20 65 
54 78 56 89 
10 93 91 90 

Java Program to sort 2D Matrix according to any Column

The idea is to use Arrays.sort in Java.

Syntax:

Arrays.sort(arr, (a,b)->a[0]-b[0]);

Example:


Output
39 27 11 42 
24 64 20 65 
54 78 56 89 
10 93 91 90 

Explanation of the above Program:

  • If element at 0 index of array a is greater than element at 0 index of array b, their difference will be positive. This means array a is kept after array b.
  • If element at 0 index of array a is smaller than element at 0 index of array b, their difference will be negative. This means array b is kept after array a.
  • If both the elements are equal, then their difference will be 0. This means that they will be equally placed.
  • On the basis of these values, the entire array is sorted.

Time complexity: O(n log n) where n is the number of rows.

Comment
Article Tags: