# Sorting with Custom Comparators

Authors: Darren Yao, Siyong Huang, Michael Cao, Benjamin Qi

If we use custom objects or if we want to sort elements in an order other than the default, then we'll need to define a custom comparator.

Resources | |||
---|---|---|---|

IUSACO | partially based off this | ||

CPH | short overview of what this module will cover |

## Example: Wormhole Sort

Focus Problem â€“ read through this problem before continuing!

We won't discuss the full solution here, as some of the concepts necessary for solving this problem will be introduced later in Silver. However, many solutions to this problem start by sorting the edges in nondecreasing order of weight. For example, the sample contains the following edges:

1 2 9 1 3 7 2 3 10 2 4 3

After sorting, it should look like

2 4 3 1 3 7 1 2 9 2 3 10

With C++, the easiest method is to use a `vector`

of nested `pair`

s:

#include <bits/stdc++.h>using namespace std;#define f first#define s secondint main() {int M = 4;vector<pair<int,pair<int,int>>> v;for (int i = 0; i < M; ++i) {

or a `vector`

of `array<int,3>`

s or `vector<int>`

s:

int main() {int M = 4;vector<array<int,3>> v; // or vector<vector<int>>for (int i = 0; i < M; ++i) {int a,b,w; cin >> a >> b >> w;v.push_back({w,a,b});}sort(begin(v),end(v));for (auto e: v) cout << e[1] << " " << e[2] << " " << e[0] << "\n";}

In Python, we can use a list of lists.

But in Java, we can't sort an `ArrayList`

of `ArrayList`

s without writing some additional code. What should we do?

- If we only stored the edge weights and sorted them, we would have a sorted list of edge weights, but it would be impossible to tell which weights corresponded to which edges.
- However, if we create a
**class**representing the edges and define a**custom comparator**to sort them by weight, we can sort the edges in ascending order while also keeping track of their endpoints.

## Classes

First, we need to define a **class** that represents what we want to sort. In our example we will define a class `Edge`

that contains the two endpoints of the edge and the weight.

C++

### C++

A C++ `struct`

is the same as a `class`

in C++, but all members are public by default.

#include <bits/stdc++.h>using namespace std;struct Edge {int a,b,w;};/* alternatively,class Edge {public:

Java

import java.util.*;public class Sol {static class Edge {int a,b,w;public Edge(int _a, int _b, int _w) { a = _a; b = _b; w = _w; }}public static void main(String[] args) {int M = 4;Scanner in = new Scanner(System.in);

Python

class Edge:def __init__(self, a, b, w):self.a = aself.b = bself.w = wv = []M = 4for i in range(M):a,b,w = map(int,input().split())v.append(Edge(a,b,w))for e in v:print(e.a,e.b,e.w)

## Comparators

Normally, sorting functions rely on moving objects with a lower value in front of objects with a higher value if sorting in ascending order, and vice versa if in descending order. This is done through comparing two objects at a time.

C++

What a comparator does is compare two objects as follows, based on our comparison criteria:

- If object $x$ is less than object $y$, return
`true`

- If object $x$ is greater than or equal to object $y$, return
`false`

Essentially, the comparator determines whether object $x$ belongs to the left of object $y$ in a sorted ordering. A comparator **must** return false for two identical objects (not doing so results in undefined behavior and potentially a runtime error).

In addition to returning the correct answer, comparators should also satisfy the following conditions:

- The function must be consistent with respect to reversing the order of the arguments: if $x \neq y$ and
`compare(x, y)`

is`true`

, then`compare(y, x)`

should be`false`

and vice versa. - The function must be transitive. If
`compare(x, y)`

is true and`compare(y, z)`

is true, then`compare(x, z)`

should also be true. If the first two compare functions both return`false`

, the third must also return`false`

.

### Method 1: Overloading the Less Than Operator

This is the easiest to implement. However, it only works for objects (not primitives) and it doesn't allow you to define multiple ways to compare the same type of class.

In the context of Wormhole Sort (note the use of const Edge&):

#include <bits/stdc++.h>using namespace std;struct Edge {int a,b,w;bool operator<(const Edge& y) { return w < y.w; }};int main() {int M = 4;

We can also overload the operator outside of the class:

struct Edge {int a,b,w;};bool operator<(const Edge& x, const Edge& y) { return x.w < y.w; }

or within it using friend:

struct Edge {int a,b,w;friend bool operator<(const Edge& x, const Edge& y) { return x.w < y.w; }};

### Method 2: Comparison Function

This works for both objects and primitives, and you can declare many different comparators for the same object.

#include <bits/stdc++.h>using namespace std;struct Edge {int a,b,w;};bool cmp(const Edge& x, const Edge& y) { return x.w < y.w; }int main() {

We can also use lambda expressions in C++11 or above:

sort(begin(v),end(v),[](const Edge& x, const Edge& y) { return x.w < y.w; });

Java

What a `Comparator`

does is compare two objects as follows, based on our comparison criteria:

- If object $x$ is less than object $y$, return a negative integer.
- If object $x$ is greater than object $y$, return a positive integer.
- If object $x$ is equal to object $y$, return 0.

In addition to returning the correct number, comparators should also satisfy the following conditions:

- The function must be consistent with respect to reversing the order of the arguments: if
`compare(x, y)`

is positive, then`compare(y, x)`

should be negative and vice versa. - The function must be transitive. If
`compare(x, y) > 0`

and`compare(y, z) > 0`

, then`compare(x, z) > 0`

. Same applies if the compare functions return negative numbers. - Equality must be consistent. If
`compare(x, y) = 0`

, then`compare(x, z)`

and`compare(y, z)`

must both be positive, both negative, or both zero. Note that they don't have to be equal, they just need to have the same sign.

Java has default functions for comparing `int`

, `long`

, `double`

types. The `Integer.compare()`

, `Long.compare()`

, and `Double.compare()`

functions take two arguments $x$ and $y$ and compare them as described above.

There are two ways of implementing this in Java: `Comparable`

, and `Comparator`

. They essentially serve the same purpose, but `Comparable`

is generally easier and shorter to code. `Comparable`

is a function implemented within the class containing the custom object, while `Comparator`

is its own class.

### Method 1: Comparable

We'll need to put `implements Comparable<Edge>`

into the heading of the class. Furthermore, we'll need to implement the `compareTo`

method. Essentially, `compareTo(x)`

is the `compare`

function that we described above, with the object itself as the first argument, or `compare(self, x)`

.

When using Comparable, we can just call `Arrays.sort(arr)`

or `Collections.sort(list)`

on the array or list as usual.

import java.util.*;public class Sol {static class Edge implements Comparable<Edge> {int a,b,w;public Edge(int _a, int _b, int _w) { a = _a; b = _b; w = _w; }public int compareTo(Edge y) { return Integer.compare(w,y.w); }}public static void main(String[] args) {int M = 4;

### Method 2: Comparator

If instead we choose to use `Comparator`

, we'll need to declare a second class that implements `Comparator<Edge>`

:

import java.util.*;public class Sol {static class Edge {int a,b,w;public Edge(int _a, int _b, int _w) { a = _a; b = _b; w = _w; }}static class Comp implements Comparator<Edge> {public int compare(Edge a, Edge b) {return Integer.compare(a.w, b.w);

When using `Comparator`

, the syntax for using the built-in sorting function requires a second argument: `Arrays.sort(arr, new Comp())`

, or `Collections.sort(list, new Comp())`

.

Python

### Defining Less Than Operator

class Edge:def __init__(self, a, b, w):self.a = aself.b = bself.w = wdef __lt__(self, other): # lt means less thanreturn self.w < other.wv = []M = 4

### Key Function

This method maps an object to another comparable datatype with which to be sorted. This is the preferred method if you are only sorting something once. In this case we map edges to their weights.

class Edge:def __init__(self, a, b, w):self.a = aself.b = bself.w = wv = []M = 4for i in range(M):a,b,w = map(int,input().split())v.append(Edge(a,b,w))v.sort(key=lambda x:x.w)for e in v:print(e.a,e.b,e.w)

### Comparison Function

A comparison function in Python must satisfy the same properties as a comparator in Java. Note that old-style cmp functions are no longer supported, so the comparison function must be converted into a key function with `cmp_to_key`

. Most of the time, it is better to use the key function, but in the rare case that the comparison function is not easily represented as a key function, we can use this.

from functools import cmp_to_keyclass Edge:def __init__(self, a, b, w):self.a = aself.b = bself.w = wv = []M = 4

## Variations

### Sorting in Decreasing Order of Weight

We can replace all occurrences of `x.w < y.w`

with `x.w > y.w`

in our C++ code. Similarly, we can replace all occurrences of `Integer.compare(x, y)`

with `-Integer.compare(x, y)`

in our Java code. In Python, we can pass the parameter `reverse=True`

to the `sort`

or `sorted`

function.

### Sorting by Two Criteria

Now, suppose we wanted to sort a list of `Edge`

s in ascending order, primarily by weight and secondarily by first vertex (`a`

). We can do this quite similarly to how we handled sorting by one criterion earlier. What the comparator function needs to do is to compare the weights if the weights are not equal, and otherwise compare first vertices.

C++

struct Edge {int a,b,w;bool operator<(const Edge& y) {if (w != y.w) return w < y.w;return a < y.a;}};

Java

static class Edge implements Comparable<Edge> {int a,b,w;public Edge(int _a, int _b, int _w) { a = _a; b = _b; w = _w; }public int compareTo(Edge y) {if (w != y.w) return Integer.compare(w,y.w);return Integer.compare(a,y.a);}}

Python

In Python, tuples have a natural order based on their elements in order. We can take advantage of this to write a comparator:

class Edge:def __init__(self, a, b, w):self.a = aself.b = bself.w = wdef __lt__(self, other): # lt means less thanreturn (self.w, self.a) < (other.w, other.a)

This also gives an easy way to write a key function to sort in this way:

edges: list[Edge]edges.sort(key=lambda edge: (edge.w, edge.a))

Sorting by an arbitrary number of criteria is done similarly.

C++

Java

With Java, we can implement a comparator for arrays of arbitrary length (although this might be more confusing than creating a separate class).

import java.util.*;public class Sol {static class Comp implements Comparator<int[]> {public int compare(int[] a, int[] b){for (int i = 0; i < a.length; ++i)if (a[i] != b[i]) return Integer.compare(a[i],b[i]);return 0;}}

Python

## Problems

Status | Source | Problem Name | Difficulty | Tags | Solution | URL |
---|---|---|---|---|---|---|

CSES | Easy | |||||

Silver | Easy | |||||

Silver | Normal | |||||

Silver | Normal | External Sol | ||||

Silver | Normal | |||||

Gold | Normal | |||||

Silver | Hard | External Sol | ||||

Silver | Hard | External Sol | ||||

Silver | Very Hard | External Sol |

### Module Progress:

### Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

## Give Us Feedback on Sorting with Custom Comparators!

Leave suggestions for us by making a post on the USACO Forum! Ex: Unclear sections, mislabeled problems, etc.