Java Sorting a 2D Array Rows into Ascending and Columns into Descending Order

Sorting 2D array in ascending order using java with respect to first row alone

Firstly, reading columns in a 2-D Array as 1-D Array is not possible. It can only be done for rows.

As per your code, you are comparing o2[1] and o1[1] which means you are comparing 2nd element in both the rows which is not your requirement.

You better transpose the the matrix and apply the same logic by comparing o2[0] and o1[0] and finally transpose the matrix again to get the desired result..

java Arrays.sort 2d array

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
public int compare(double[] a, double[] b) {
return Double.compare(a[0], b[0]);
}
});

JAVA-8: Instead of that big comparator, we can use lambda function as following-

Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));

2D array integer column in descending order

Try this:

public static void main(String[] args) throws IOException {
//Read text file
FileReader fr = new FileReader("primary1.txt");
BufferedReader br = new BufferedReader(fr);

//2D array
String[][] primary = new String[44][5];

//Section break
System.out.println("1. The file contents are:\n");

//Add column titles
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");

//Set delimiter as "/"
String line;
int i=0;
while((line=br.readLine())!=null){
primary[i]=line.split("/");
i++;
}

//Print text file
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}

//Clinton's delegates in order from highest to lowest
for(int row=0; row<primary.length-1; row++){
for(int row1=row+1; row1<primary.length; row1++) {
//Parse Integer
int delC = Integer.parseInt(primary[row][2]);
int delC1 = Integer.parseInt(primary[row1][2]);
if(delC < delC1){
String[]tmpprimary = primary[row];
primary[row] = primary[row1];
primary[row1] = tmpprimary;
}
}
}
System.out.println("\n**************************** Order Descending *******************************");
System.out.println("States\t\t\t\tCandidate#1\tVotes\t\tCandidate#2\tVotes");
for(int row=0; row<primary.length; row++){
for(int col=0; col<primary[row].length; col++){
//Add space between columns
System.out.print(primary[row][col] + "\t\t");
}
//Newline
System.out.println();
}
}

How to sort a 2D array in increasing order? Java

It seems that you want to sort each line of your matrix.
You could simply go over each line and sort using off-the-shelf java method, given a is a two dimensional array :

for (i = 0; i < a.length; i++) {
Arrays.sort(a[i]);
}

Anyway your question is not crystal clear to me and I join @Normr on its comment.



Related Topics



Leave a reply



Submit