bpo-36095: Better NaN sorting. #12001
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Sorting sequences containing
NaN
values produces an incompletely sorted result. Further, because of the complexity of the timsort, this incomplete sort often silently produces unintuitive, unstable-seeming results that are extremely sensitive to the ordering of the inputs:The patch I have provided addresses these issues, including for lists containing nested lists/tuples with
NaN
values. Specifically, it stably sortsNaN
s to the end of the list with no changes to the timsort itself (just the element-wise comparison functions):It also includes a new regression test for this behavior.
Some other benefits to this patch:
These changes generally result in a sorting performance improvement across data types. The largest increases here are for nested lists, since we add a new
unsafe_list_compare
function. Other speed increases are due tosafe_object_compare
's delegation to unsafe comparison functions for objects of the same type. Specifically, the speed impact (positive is faster, negative is slower) is between:The current weird
NaN
-sorting behavior is not documented, so this is not a breaking change.IEEE754 compliance is maintained. The result is still a stable (arguably, more stable), nondecreasing ordering of the original list.
https://bugs.python.org/issue36095