It is necessary to sort the pairs, first by the first element (as in the code), and then by the second. That is, if the first elements of the pairs coincide, then it is necessary to sort by the second. thank
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); Pair mas[] = new Pair[n]; for(int i = 0; i < n; i++) { mas[i] = new Pair(in.nextInt(), in.nextInt()); } Arrays.sort(mas, (left, right)-> left.a - right.a); } } class Pair { final int a; final int b; public Pair(int a, int b){ this.a = a; this.b = b; } }