一键导入
algo-sorting
Sorting — when to call the built-in, when to roll your own (counting / radix / heap), stability, custom comparators.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Sorting — when to call the built-in, when to roll your own (counting / radix / heap), stability, custom comparators.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Breadth-first search — shortest path on unweighted graphs, level-order traversal, and the `visited` discipline that prevents O(2^n) blowups.
Binary search invariants, half-open intervals, and the `lo<hi` template that beats off-by-one bugs.
Depth-first search — recursive vs iterative, recursion-depth gotchas, three-color cycle detection, topological sort.
Dynamic programming — state design, memoization vs tabulation, dimension-reduction, and when DP is the wrong tool.
Pick the right traversal — BFS for unweighted shortest path, Dijkstra for weighted, A* for goal-directed, 0/1-BFS for binary weights.
Greedy algorithms — exchange-argument proofs, when greedy beats DP, classic patterns (interval scheduling, Huffman, scheduling).
| name | algo-sorting |
| description | Sorting — when to call the built-in, when to roll your own (counting / radix / heap), stability, custom comparators. |
| when-to-use | Pre-sort for two-pointer / binary-search, top-k via heap, kth-smallest via quickselect, custom-key ordering. |
sort() first, custom rarelyPython's list.sort and JavaScript's Array.prototype.sort are
both Timsort variants — O(n log n) worst case, stable. Reach for
a custom sort only when you need a different time/space trade
(counting sort for small integer ranges) or you cannot afford the
copy (heap-based top-k).
list.sort() and recent Array.prototype.sort are
stable; older JS engines were not (pre-2019).None in Python (list.sort); use
sorted() for a new list. JS arr.sort() mutates and returns
the array.O(n log n) worst, O(n) best on
near-sorted input.O(n) average, O(n^2) worst.O(n log k) time, O(k) extra space.O(n + r) for value range r — beats comparison
sort when r is small (e.g. 0..255).O(n × d) for d digits — strings of bounded
length, fixed-precision integers.# Sort by score descending, then by name ascending. Stability is
# implicit: equal-tuple rows keep insertion order.
records.sort(key=lambda r: (-r.score, r.name))
# Stability lets you also chain single-key sorts:
records.sort(key=lambda r: r.name) # secondary
records.sort(key=lambda r: r.score, reverse=True) # primary
Use a tuple key when you can — it is cleaner and roughly twice as
fast as functools.cmp_to_key. Reach for cmp_to_key only when
the comparison is non-transitive in tuple form (rare; one classic
case is "biggest-number-by-concatenation").
import heapq
def top_k_largest(arr: list[int], k: int) -> list[int]:
"""The ``k`` largest elements (in arbitrary order)."""
if k <= 0: return []
return heapq.nlargest(k, arr)
def top_k_smallest_by_key(items, k, key):
return heapq.nsmallest(k, items, key=key)
heapq.nsmallest/nlargest are O(n log k) and avoid sorting
the whole list when k << n.
// Numeric sort — default is lexicographic, which is wrong for numbers.
arr.sort((a, b) => a - b);
// Multi-key: descending score, then ascending name.
records.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
localeCompare is the right tool for human-language strings. For
ASCII identifiers, the </> operators are faster.
[10, 2, 1].sort()
gives [1, 10, 2]. Always pass a comparator for numbers.for i in range(len(arr)): if pred(arr[i]): arr.remove(...)
shifts indices and skips elements. Sort first and walk with a
write index instead.list.sort() returns None in Python. x = arr.sort() sets
x = None. Use sorted(arr) to get a new list.sort((a, b) => a > b) returns
true/false (1/0 in numeric coercion) — non-transitive, breaks
stability. Return a - b or cmp(a, b).For "median in a stream", reach for two heaps (min + max). For
"kth smallest", quickselect or nsmallest is faster than sort+index.