我想在Java中建立一种方法,以根据多个给定列中的值对数组进行排序。让我用一个示例(矩阵数组)进行解释:
int matrix[][] = {{0,2,432},{1,1,282},{2,2,456},{3,4,191},{4,5,293},{5,2,475},{6,2,491},{7,5,171},{8,5,134},{9,3,354}};
我需要根据第二个位置以降序对每个三元组进行排序。之后,我需要根据第三个位置以递增顺序对三元组进行排序。
我为此使用的代码是:
import java.util.*;
public 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) {
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[][] = {{0,2,432},{1,1,282},{2,2,456},{3,4,191},{4,5,293},{5,2,475},{6,2,491},{7,5,171},{8,5,134},{9,3,354}};
// Sort this matrix by 2rd Column
int col = 2;
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();
}
}
}
前面描述的代码的输出是:
[[8,5,134],[7,5,171],[4,5,293],[3,4,191],[9,3,354],[6,2,491],[5,2,475],[2,2,456],[0,2,432],[1,1,282]]
但是所需的输出必须是:
[[8,5,134],[7,5,171],[4,5,293],[3,4,191],[9,3,354],[0,2,432],[2,2,456],[5,2,475],[6,2,491],[1,1,282]]
请注意,根据第二个位置,我们有以下内容:5,5,5,4,3,2,2,2,2,2,1(递减顺序),根据第三个位置,顺序是:134,171,293(对于在“第二位置”为“ 5”的三元组),191(对于在第二位置为“ 4”的三元组),354(对于在第二位置为“ 3”的三元组),432,456,475,491(对于具有(第二个位置的“ 2”),最后是三元组的282,第二个位置的“ 1”。
任何帮助将不胜感激。谢谢。
从sortByColumn方法中删除col参数,因为它实际上不是参数,并以这种方式更改方法:
// Function to sort by column
public static void sortbyColumn(int arr[][])
{
// 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) {
if (entry1[1] < entry2[1])
return 1;
else if (entry1[1] > entry2[1])
return -1;
return -1 * Integer.valueOf(entry2[2]).compareTo(Integer.valueOf(entry1[2]));
}
}); // End of function call sort().
}
当然把主叫改为 sortbyColumn(matrix);
仅在与第二列相等的情况下才需要与第三列进行比较(这意味着第一个比较数值结果等于0)。在这种情况下,我们以相反的顺序进行比较,可以通过将比较结果乘以-1来获得
结果:
8 5 134 7 5 171 4 5 293 3 4 191 9 3 354 0 2432 2 2 456 5 2 475 6 2 491 1 1 282
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句