Sort by several keys in Python, Java, C++ and JavaScript.
A comparator must be consistent: it never says a row comes before itself, and it never contradicts its own earlier answers.
Use it when rows have more than one field and ties in the first field need a second rule. Signal words: then by, ties, highest first, a custom order.
Start: list the keys from the most to the least important, and say whether each runs up or down.
Step: build a key tuple, or write a comparator that tests the first key, and only on a tie the next. Or sort by the minor key first and the major key second, with a stable sort.
Stop: when the sort returns. Check the rule on a tie, on an empty list and on the largest values.
It does not help when the keys are small whole numbers and the data is huge: counting sort is faster there.
Cost: O(n log n) comparisons for one sort, and the same for each pass of a multi-pass sort.
def sort_payouts(names, units):
# [1] Pair each name with its units, so one row carries both keys.
rows = list(zip(names, units))
# [2] Sort by units from high to low, then by name from A to Z. State the rule once, as a key or a comparator.
rows.sort(key=lambda row: (-row[1], row[0]))
# [3] Return the names in the new order.
return [name for name, _ in rows]public String[] sortPayouts(String[] names, int[] units) {
// [1] Pair each name with its units, so one row carries both keys.
Integer[] rows = new Integer[names.length];
for (int i = 0; i < rows.length; i++) {
rows[i] = i;
}
// [2] Sort by units from high to low, then by name from A to Z. State the rule once, as a key or a comparator.
Arrays.sort(rows, Comparator.comparingInt((Integer i) -> units[i]).reversed().thenComparing(i -> names[i]));
// [3] Return the names in the new order.
String[] result = new String[rows.length];
for (int i = 0; i < rows.length; i++) {
result[i] = names[rows[i]];
}
return result;
}vector<string> sortPayouts(const vector<string>& names, const vector<int>& units) {
// [1] Pair each name with its units, so one row carries both keys.
vector<int> rows(names.size());
iota(rows.begin(), rows.end(), 0);
// [2] Sort by units from high to low, then by name from A to Z. State the rule once, as a key or a comparator.
sort(rows.begin(), rows.end(), [&](int a, int b) {
if (units[a] != units[b]) {
return units[a] > units[b];
}
return names[a] < names[b];
});
// [3] Return the names in the new order.
vector<string> result;
for (int row : rows) {
result.push_back(names[row]);
}
return result;
}function sortPayouts(names, units) {
// [1] Pair each name with its units, so one row carries both keys.
const rows = names.map((_, i) => i);
// [2] Sort by units from high to low, then by name from A to Z. State the rule once, as a key or a comparator.
rows.sort((a, b) => {
if (units[a] !== units[b]) {
return units[b] - units[a];
}
return names[a] < names[b] ? -1 : names[a] > names[b] ? 1 : 0;
});
// [3] Return the names in the new order.
return rows.map((row) => names[row]);
}def sort_payouts_two_pass(names, units):
# [1] Pair each name with its units, so one row carries both keys.
rows = list(zip(names, units))
# [2] First pass: sort by the minor key, the name from A to Z.
rows.sort(key=lambda row: row[0])
# [3] Second pass: a stable sort by the major key, units from high to low. Equal units keep the name order.
rows.sort(key=lambda row: row[1], reverse=True)
# [4] Return the names in the new order.
return [name for name, _ in rows]public String[] sortPayoutsTwoPass(String[] names, int[] units) {
// [1] Pair each name with its units, so one row carries both keys.
Integer[] rows = new Integer[names.length];
for (int i = 0; i < rows.length; i++) {
rows[i] = i;
}
// [2] First pass: sort by the minor key, the name from A to Z.
Arrays.sort(rows, Comparator.comparing((Integer i) -> names[i]));
// [3] Second pass: a stable sort by the major key, units from high to low. Equal units keep the name order.
Arrays.sort(rows, Comparator.comparingInt((Integer i) -> units[i]).reversed());
// [4] Return the names in the new order.
String[] result = new String[rows.length];
for (int i = 0; i < rows.length; i++) {
result[i] = names[rows[i]];
}
return result;
}vector<string> sortPayoutsTwoPass(const vector<string>& names, const vector<int>& units) {
// [1] Pair each name with its units, so one row carries both keys.
vector<int> rows(names.size());
iota(rows.begin(), rows.end(), 0);
// [2] First pass: sort by the minor key, the name from A to Z.
stable_sort(rows.begin(), rows.end(), [&](int a, int b) { return names[a] < names[b]; });
// [3] Second pass: a stable sort by the major key, units from high to low. Equal units keep the name order.
stable_sort(rows.begin(), rows.end(), [&](int a, int b) { return units[a] > units[b]; });
// [4] Return the names in the new order.
vector<string> result;
for (int row : rows) {
result.push_back(names[row]);
}
return result;
}function sortPayoutsTwoPass(names, units) {
// [1] Pair each name with its units, so one row carries both keys.
const rows = names.map((_, i) => i);
// [2] First pass: sort by the minor key, the name from A to Z.
rows.sort((a, b) => (names[a] < names[b] ? -1 : names[a] > names[b] ? 1 : 0));
// [3] Second pass: a stable sort by the major key, units from high to low. Equal units keep the name order.
rows.sort((a, b) => units[b] - units[a]);
// [4] Return the names in the new order.
return rows.map((row) => names[row]);
}from functools import cmp_to_key
def join_largest(parts):
# [1] The comparator puts piece a before piece b when a + b makes the larger text.
def compare(a, b):
if a + b > b + a:
return -1
if a + b < b + a:
return 1
return 0
# [2] Sort the pieces with the comparator.
ordered = sorted(parts, key=cmp_to_key(compare))
# [3] Join the pieces. A leading zero means every piece was zero, so the answer is "0".
joined = "".join(ordered)
return "0" if joined.startswith("0") else joinedpublic String joinLargest(String[] parts) {
// [1] The comparator puts piece a before piece b when a + b makes the larger text.
Comparator<String> byJoin = (a, b) -> (b + a).compareTo(a + b);
// [2] Sort the pieces with the comparator.
String[] ordered = parts.clone();
Arrays.sort(ordered, byJoin);
// [3] Join the pieces. A leading zero means every piece was zero, so the answer is "0".
String joined = String.join("", ordered);
return joined.startsWith("0") ? "0" : joined;
}string joinLargest(const vector<string>& parts) {
// [1] The comparator puts piece a before piece b when a + b makes the larger text.
auto byJoin = [](const string& a, const string& b) { return a + b > b + a; };
// [2] Sort the pieces with the comparator.
vector<string> ordered = parts;
sort(ordered.begin(), ordered.end(), byJoin);
// [3] Join the pieces. A leading zero means every piece was zero, so the answer is "0".
string joined;
for (const string& piece : ordered) {
joined += piece;
}
return (!joined.empty() && joined[0] == '0') ? "0" : joined;
}function joinLargest(parts) {
// [1] The comparator puts piece a before piece b when a + b makes the larger text.
const byJoin = (a, b) => (a + b > b + a ? -1 : a + b < b + a ? 1 : 0);
// [2] Sort the pieces with the comparator.
const ordered = [...parts].sort(byJoin);
// [3] Join the pieces. A leading zero means every piece was zero, so the answer is "0".
const joined = ordered.join("");
return joined.startsWith("0") ? "0" : joined;
}This Python version writes sorted(rows, key=lambda r: (r[1], r[0]), reverse=True). It reverses the whole key, so the names also run from Z to A.
This version returns a <= b for the comparator. It says a value comes before an equal value, so it breaks the strict weak ordering that std::sort assumes. The behaviour is undefined.
This version calls .sort() on numbers with no comparator. JavaScript then compares the items as text.
This JavaScript version returns a > b. A boolean turns into 1 or 0, and never into a negative number, so the sort cannot tell "before" from "tie".
This Java version writes (p, q) -> p - q for Integer values. When the difference passes 2,147,483,647, it wraps around.
A game says rock beats scissors, scissors beats paper, and paper beats rock. No sort order fits, because the comparison goes in a circle.
systemdesignmastery.dev/dsa/cheatsheets/comparators