拜托,有人可以帮我吗,我需要按降序对2d数组列进行排序?我使用此代码将数组行按升序排序,但现在必须将列按降序排序。
// Initialize array
static int[][] sortArray = new int[7][7];
public static void main(String args[]) {
//initialize array values with random numbers
for (int i = 0; i < sortArray.length; i++) {
for (int j = 0; j < sortArray[i].length; j++) {
sortArray[i][j] = (int) (Math.random() * 100);
}
}
System.out.println("\n" + "Before sorting");
displayArray();
//Print out sorted array
for (int i = 0; i < sortArray.length; i++) {
bubbleSort(sortArray[i]);
}
System.out.println("\n" + "Array rows in ascending order");
displayArray();
//Print out sorted columns of array
for (int i = 0; i < sortArray.length; i++) {
sortSort(sortArray[i]);
}
System.out.println("\n" + "Array column in descending order");
displayArray();
}
// Sort rows into ascending order
public static void bubbleSort(int[] numArray) {
int n = numArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numArray[j - 1] > numArray[j]) {
temp = numArray[j - 1];
numArray[j - 1] = numArray[j];
numArray[j] = temp;
}
}
}
}
//Sort cols into descending order
public static void sortSort(int[] colArray) {
int n = colArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (colArray[j - 1] < colArray[j]) {
temp = colArray[j - 1];
colArray[j - 1] = colArray[j];
colArray[j] = temp;
}
}
}
}
// Print out arrays
private static void displayArray() {
int i, j = 0;
System.out.println("-------------------------------------");
System.out.println(" ");
for (i = 0; i < sortArray.length; i++) {
for (j = 0; j < sortArray[i].length; j++) {
System.out.print(sortArray[i][j] + "\t" + "\t");
}
System.out.println();
}
}
最佳答案
int[] colArray = new int[] { 2, 9, 4, 5};
int n = colArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (colArray[j - 1] > colArray[j]) {
temp = colArray[j - 1];
colArray[j - 1] = colArray[j];
colArray[j] = temp;
}
}
}
Arrays.stream(colArray).forEach(data -> System.out.println(data));