Sort an array of pairs using Java Arrays.sort() with custom Comparator
Given an array of pairs of integers. The task is to sort the array with respect to the second element of the pair.
Examples:
Input: [(1, 2), (3, 5), (2, 6), (1, 7)]
Output: [(1, 2), (3, 5), (2, 6), (1, 7)]
Input: [(10, 20), (20, 30), (5, 6), (2, 5)]
Output: [(2, 5), (5, 6), (10, 20), (20, 30)]
Approach:
- Store the pairs in an array using a user-defined Pair class.
- Override the comparator method to sort the array according to the second element.
- Sort the array according to the second element.
Below is the implementation of the above approach:
Java
import java.util.Arrays;
import java.util.Comparator;
class Pair {
int x;
int y;
public Pair( int x, int y) {
this .x = x;
this .y = y;
}
@Override
public String toString() {
return "(" + x +
", " + y +
')' ;
}
}
class ArrayOfPairsSorter {
static void sort(Pair[] arr) {
Comparator<Pair> comparator = new Comparator<>() {
@Override
public int compare(Pair p1, Pair p2) {
return p1.y
- p2.y;
}
};
Arrays.sort(arr, comparator);
}
}
class GFG {
public static void main(String[] args) {
Pair[] arr = new Pair[ 5 ];
arr[ 0 ] = new Pair( 10 , 20 );
arr[ 1 ] = new Pair( 1 , 2 );
arr[ 2 ] = new Pair( 3 , 1 );
arr[ 3 ] = new Pair( 10 , 8 );
arr[ 4 ] = new Pair( 4 , 3 );
ArrayOfPairsSorter.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
|
Output:
[(3, 1), (1, 2), (4, 3), (10, 8), (10, 20)]
Last Updated :
03 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...