Java – sort a two-dimensional array based on a row of data

I'm not sure whether the title correctly indicates the question I want to ask Suppose I have a two-dimensional int array, as follows:

int[][] x={{1,7,6},{2,4,8}};

Now I want to sort the first row in ascending order. The data in the second row must be in the same column after sorting, that is, after sorting, the array should be as follows:

x={{1,6,7},8,4}}

What is the right way to do it?

Solution

This can be done by implementing your own sorting routine, but a better way is to refactor

Try to encapsulate the data into an array of number pairs, each pair of data contained in its own object You can then sort the first value and access any value

class Pair<T extends Comparable<T>> implements Comparable<Pair<T>> {
  final T a;
  final T b;

  public Pair ( T a,T b ) {
    this.a = a;
    this.b = b;
  }

  @Override
  public int compareTo(Pair<T> o) {
    // Comparison on 'a' only.
    return a.compareTo(o.a);
  }

  @Override
  public String toString () {
    return "{" + a + "," + b + "}";
  }
}

public static void main(String args[]) {
  Pair[] pairs = {
    new Pair(1,2),new Pair(7,4),new Pair(6,8),};
  System.out.println("Before: "+Arrays.toString(pairs));
  Arrays.sort(pairs);
  System.out.println("After: "+Arrays.toString(pairs));
}

print

Before: [{1,2},{7,4},{6,8}]
After: [{1,8},4}]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>