Skip to content

Commit ecc2832

Browse files
committed
Speedup heapsort by 1.5x by making it branchless.
`slice::sort_unstable` will fall back to heapsort if it repeatedly fails to find a good pivot. By making the core child update code branchless it is much faster. On Zen3 sorting 10k `u64` and forcing the sort to pick heapsort, results in: 455us -> 278us
1 parent 5f39350 commit ecc2832

File tree

1 file changed

+1
-3
lines changed

1 file changed

+1
-3
lines changed

src/heap_sort.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@ where
2020
}
2121

2222
// Choose the greater child.
23-
if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) {
24-
child += 1;
25-
}
23+
child += (child + 1 < v.len() && is_less(&v[child], &v[child + 1])) as usize;
2624

2725
// Stop if the invariant holds at `node`.
2826
if !is_less(&v[node], &v[child]) {

0 commit comments

Comments
 (0)