Using Java, sort 2D array where first element is unique to second element. (Example:…
- User
Using Java, sort 2D array where first element is unique to second element. (Example: {[1,2],[3,4], [2,5],[6,1]} Expected outcome: {[3,4],[1,2],[2,5],[6,1]}
Assistant
Here's a Java solution to sort a 2D array based on the second element of each sub-array:
import java.util.Arrays; import java.util.Comparator; public class Array2DSort { public static void main(String[] args) { int[][] array = {{1,2}, {3,4}, {2,5}, {6,1}}; // Sort by second element (index 1) Arrays.sort(array, Comparator.comparingInt(a -> a[1])); // Print result System.out.println(Arrays.deepToString(array)); // Output: [[6, 1], [1, 2], [3, 4], [2, 5]] } }Alternative approaches:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.