特定の列を超える値に従って配列をソートするためのメソッドを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}};
すべてのトリプレットを2番目の位置に従って降順で並べ替える必要があります。その後、3番目の位置に従ってトリプレットを昇順で並べ替える必要があります。
そのために使用しているコードは次のとおりです。
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]]
2番目の位置によると次のようになります:5,5,5,4,3,2,2,2,2,1(降順)そして3番目の位置によると次のようになります:134,171,293( 2番目の位置に「5」があるトリプレット)、191(2番目の位置に「4」があるトリプレットの場合)、354(2番目の位置に「3」があるトリプレットの場合)、432,456,475,491(2番目の位置にあるトリプレットの場合) 2番目の位置に「2」)、最後に2番目の位置に「1」があるトリプレットの場合は282。
どんな助けでも大歓迎です。ありがとう。
colパラメーターは実際にはパラメーターではないため、sortByColumnメソッドから削除し、次のようにメソッドを変更します。
// 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);
2番目の列が等しい場合にのみ3番目の列で比較する必要があります(つまり、最初の比較の数値結果は0に等しくなります)。その場合、逆の順序で比較します。これは、比較結果に-1を掛けることで得られます。
結果:
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加