-1

I want to sort an 2D-array in zig-zag order using only the first number. For example:

int[][] a = {{2,5,4}{5,3,5}{56,5,54}{353,35}}
sort(a)
System.out.println(a)

What I want it to print is ((2,5,4),(56,5,54),(5,3,5),(353,35)). Is there any way to do this with a time complexity of O(n)?

This is not a duplicate because I want it in O(n).

nishantc1527
  • 376
  • 1
  • 12
  • `Arrays.sort(a, Comparator.comparingInt(i -> i[0]));` – Oleksandr Pyrohov Aug 02 '19 at 21:05
  • What's wrong with implementing it yourself? This seems like an *extremely* rare thing to do and I wouldn't expect anyone to ever have created a method for doing this in any library of any language in any universe. – RaminS Aug 02 '19 at 21:05

1 Answers1

2

You can implement a custom comparator and use the Arrays.sort method as follows:

int[][] original = new int[][]{{2,2},{1,1},{4,4},{3,3}};
Arrays.sort(original, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o1[0], o2[0]);
    }
});
System.out.println(Arrays.deepToString(original)); //[[1, 1], [2, 2], [3, 3], [4, 4]]

Pshemo
  • 122,468
  • 25
  • 185
  • 269
CastMart
  • 98
  • 5