← All lints

argsort_loop

L0582Idiomswarn

Argsort through value-index pairs

(a[i], i) pairs sorted for their order: (0..n).sorted(by: i => a[i])

Flagged
let n: 1..=200000 = read()
let a: [0..n]Int = read()
let order = [(a[i], i) for i in 0..n].sorted()
for (v, i) in order:
    print(i + 1, end: " ")
print()
Write instead
let n: 1..=200000 = read()
let a: [0..n]Int = read()
for i in (0..n).sorted(by: i => a[i]):
    print(i + 1, end: " ")
print()

Why

Sorting pairs (a[i], i) is how C++ gets the positions of a in order of value: the pair carries the position along, and the sort's tie-break on the second half keeps equal values in position order. (0..n).sorted(by: i => a[i]) says the same thing directly: sort the positions, keyed by their value. sorted is stable, so equal values keep position order exactly as the pairs did, and the result is a list of positions, so the loop over it has no (v, i) to unpack and reads a[i] where it needs it. The cost is the same O(nlog⁡n)O(n \log n). Pairs whose second half is not the position, such as (a[i], b[i]), are a real sort of pairs and are not reported. There is no automatic fix, because the code that reads the sorted pairs has to change with them.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let n: 1..=200000 = read()
let a: [0..n]Int = read()
let b: [0..n]Int = read()
let order = [(a[i], b[i]) for i in 0..n].sorted()
print(order)

Turn it off

For one block, wrap it in with lint(argsort_loop: allow):. For a project, add argsort_loop = "allow" under [lints] in cp.toml.

Generated from spec/lints/argsort_loop, the same record the linter is built from.