根据Java中任何给定列中的值对2D数组进行排序

我们得到了一个nxm阶的二维数组和一个列号K(1<=K<=M)。我们的任务是根据K列中的值对2D数组进行排序。

null

例如:

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排序 .

// Java Code to sort 2D Matrix
// according to any Column
import java.util.*;
class sort2DMatrixbycolumn {
// Function to sort by column
public static void sortbyColumn( int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator< int []>() {
@Override
// Compare values according to columns
public int compare( final int [] entry1,
final int [] entry2) {
// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1 ;
else
return - 1 ;
}
}); // End of function call sort().
}
// Driver Code
public static void main(String args[])
{
int matrix[][] = { { 39 , 27 , 11 , 42 },
{ 10 , 93 , 91 , 90 },
{ 54 , 78 , 56 , 89 },
{ 24 , 64 , 20 , 65 } };
// Sort this matrix by 3rd Column
int col = 3 ;
sortbyColumn(matrix, col - 1 );
// Display the sorted Matrix
for ( int i = 0 ; i < matrix.length; i++) {
for ( int j = 0 ; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " " );
System.out.println();
}
}
}


输出:

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

时间复杂性 :O(n logn),其中n是行数。这里假设sort()函数使用O(n logn)排序算法。

本文由 丹麦卡里姆 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享