Please, can someone help me, I need to sort my 2d array columns into descending order? I used this code to sort my array rows into ascending order but I now have to sort the columns into descending.
// 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();
}
}
colArrayis not a 2D array .int[][] colArray, so that method will only work for a normal arraycolArrayexactly? I guess it represents one column of a 2D-array, likeint[][] fullArray? Then colArray would be:int[] colArray = fullArray[i]?