Return the top k values per row, sorted, with stable tie breaking
Retrievers and samplers need the k best scores per row. A full sort costs n log n per row; argpartition finds the top k in linear time and you only sort those k.
Write topk_rows(X, k) for a 2D float array and 1 <= k <= number of columns. Return (values, indices), both shape (rows, k), sorted by value from largest to smallest. When values tie, the smaller column index comes first, so results are deterministic.
def topk_rows(X, k)Example
topk_rows([[1, 3, 3, 0]], 2) gives values [[3, 3]] and indices [[1, 2]].
Understand the idea
Retrievers and samplers often need the k largest scores in each row. A full sort is more work than needed; argpartition can find the top k in linear time, and then you sort only those k. Ties must be broken the same way every time: equal values keep the smaller column index first. Worked example: X = [[2, 5, 5, 1, 5]], k = 2. The three 5s are at columns 1, 2 and 4. The top 2 values are 5 and 5, and by the tie rule the indices are [1, 2], not [2, 4] or [4, 1]. values = [[5, 5]], indices = [[1, 2]]. Rule: for each row, choose the k largest values; order them from largest to smallest; among equal values, lower column index first. A stable sort on the negated values gives exactly this order. Reversing an ascending stable sort is the classic mistake, because it flips tied items so larger indices win. Watch out too: argpartition alone does not respect ties, so after it you still need a careful sort, or a stable full sort per row. Used for top-k sampling and nearest neighbour retrieval.