Sorting a two dimensional array on the basis of one row data

arrays, java

Solution

This can be done by implementing your own sort routine but a better approach would be to refactor.

Try encapsulating the data as an array of pairs of numbers, each pair wrapped in its own object. You can then sort on the first value and access either 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));
}

prints

Before: [{1,2}, {7,4}, {6,8}]
After: [{1,2}, {6,8}, {7,4}]

Problem

I am not sure if the title rightly suggests what I am trying to ask. Let's say I have a two dimensional int array as below: ``` int[][] x={{1,7,6},{2,4,8}}; ``` Now I want to sort the first row in ascending order and the data in the 2nd row must be in the same column after the sorting, i.e., after sorting, the array should be like this: ``` x={{1,6,7},{2,8,4}} ``` What is the right way to do it?

Original source