Commit 0fe977c4 authored by Tim Peters's avatar Tim Peters

binarysort() cleanup: Documented the key invariants, explained why they

imply this is a stable sort, and added some asserts.
parent 326b4487
...@@ -871,14 +871,25 @@ binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare) ...@@ -871,14 +871,25 @@ binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
l = lo; l = lo;
r = start; r = start;
pivot = *r; pivot = *r;
/* Invariants:
* pivot >= all in [lo, l).
* pivot < all in [r, start).
* The second is vacuously true at the start.
*/
assert(l < r);
do { do {
p = l + ((r - l) >> 1); p = l + ((r - l) >> 1);
IFLT(pivot, *p) IFLT(pivot, *p)
r = p; r = p;
else else
l = p + 1; l = p+1;
} while (l < r); } while (l < r);
/* Pivot should go at l -- slide over to make room. assert(l == r);
/* The invariants still hold, so pivot >= all in [lo, l) and
pivot < all in [l, start), so pivot belongs at l. Note
that if there are elements equal to pivot, l points to the
first slot after them -- that's why this sort is stable.
Slide over to make room.
Caution: using memmove is much slower under MSVC 5; Caution: using memmove is much slower under MSVC 5;
we're not usually moving many slots. */ we're not usually moving many slots. */
for (p = start; p > l; --p) for (p = start; p > l; --p)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment