Skip to content

Commit 5103173

Browse files
committed
Auto merge of #117179 - Voultapher:fix-useless-comp-in-partition-equal, r=Mark-Simulacrum
Avoid unnecessary comparison in partition_equal The branchy Hoare partition `partition_equal` as part of `slice::sort_unstable` has a bug that makes it perform a comparison of the last element twice. Measuring inputs with a Zipfian distribution with characterizing exponent s == 1.0, yields a ~0.05% reduction in the total number of comparisons performed.
2 parents 6c7de31 + e501add commit 5103173

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

Diff for: library/core/src/slice/sort.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -628,9 +628,14 @@ where
628628
let _pivot_guard = InsertionHole { src: &*tmp, dest: pivot };
629629
let pivot = &*tmp;
630630

631+
let len = v.len();
632+
if len == 0 {
633+
return 0;
634+
}
635+
631636
// Now partition the slice.
632637
let mut l = 0;
633-
let mut r = v.len();
638+
let mut r = len;
634639
loop {
635640
// SAFETY: The unsafety below involves indexing an array.
636641
// For the first one: We already do the bounds checking here with `l < r`.
@@ -643,8 +648,11 @@ where
643648
}
644649

645650
// Find the last element equal to the pivot.
646-
while l < r && is_less(pivot, v.get_unchecked(r - 1)) {
651+
loop {
647652
r -= 1;
653+
if l >= r || !is_less(pivot, v.get_unchecked(r)) {
654+
break;
655+
}
648656
}
649657

650658
// Are we done?
@@ -653,7 +661,6 @@ where
653661
}
654662

655663
// Swap the found pair of out-of-order elements.
656-
r -= 1;
657664
let ptr = v.as_mut_ptr();
658665
ptr::swap(ptr.add(l), ptr.add(r));
659666
l += 1;

0 commit comments

Comments
 (0)