An implementation notebook · KNN / KD-tree

Inside a KD-tree.

Move one decision at a time. See how rows become groups, how groups become bounds, and how a heap turns those bounds into permission to skip work.

Works offline · no setup

Find one position without sorting every position.

A trial pivot earns its rank by comparisons. Watch the row indices move while the original feature values stay attached to their rows.

Teaching Quickselect
Trial pivotRow being comparedRequested positionFaded = excluded from further selection

Try Back after a swap. The row ID travels with its value. No row is deleted or replaced.

The rule that makes this possible

A count gives the pivot its rank.

If exactly three rows precede a pivot, the pivot belongs in the fourth position. Those three rows can remain internally unordered.

For equal values, compare original row IDs next. This reproduces the ordering rule in sklearn’s partition comparator.

What does sklearn actually request?

std::nth_element(
    start_of_indices,
    required_position,
    end_of_indices,
    compare_rows
);

std names the C++ standard library’s namespace. :: accesses a name inside it. The function rearranges indices in place.

This animation uses last-element pivots so every step is visible. The C++ library used to build sklearn chooses its own selection procedure. These are illustrative swaps, not a recording of its binary.