diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-09-25-23-26-15.gh-issue-138946.uN03eR.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-09-25-23-26-15.gh-issue-138946.uN03eR.rst new file mode 100644 index 00000000000000..721a5f5f9d5b35 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2025-09-25-23-26-15.gh-issue-138946.uN03eR.rst @@ -0,0 +1 @@ +Make binarysort adaptative. This improve sorting() performance by reducing the amount of comparisons of already sorted intervals. diff --git a/Objects/listobject.c b/Objects/listobject.c index 5905a6d335b311..39fb3b208c72e5 100644 --- a/Objects/listobject.c +++ b/Objects/listobject.c @@ -1829,6 +1829,7 @@ binarysort(MergeState *ms, const sortslice *ss, Py_ssize_t n, Py_ssize_t ok) } #else // binary insertion sort Py_ssize_t L, R; + M = ok - 1; // Start with the element close to the pivot for (; ok < n; ++ok) { /* set L to where a[ok] belongs */ L = 0; @@ -1841,14 +1842,14 @@ binarysort(MergeState *ms, const sortslice *ss, Py_ssize_t n, Py_ssize_t ok) */ assert(L < R); do { - /* don't do silly ;-) things to prevent overflow when finding - the midpoint; L and R are very far from filling a Py_ssize_t */ - M = (L + R) >> 1; #if 1 // straightforward, but highly unpredictable branch on random data IFLT(pivot, a[M]) R = M; else L = M + 1; + /* don't do silly ;-) things to prevent overflow when finding + the midpoint; L and R are very far from filling a Py_ssize_t */ + M = (L + R) >> 1; #else /* Try to get compiler to generate conditional move instructions instead. Works fine, but leaving it disabled for now because