Skip to content

Optimize heapsort #93765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 20, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions library/core/src/slice/sort.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,22 +188,25 @@ where
// This binary heap respects the invariant `parent >= child`.
let mut sift_down = |v: &mut [T], mut node| {
loop {
// Children of `node`:
let left = 2 * node + 1;
let right = 2 * node + 2;
// Children of `node`.
let mut child = 2 * node + 1;
if child >= v.len() {
break;
}

// Choose the greater child.
let greater =
if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) {
child += 1;
}

// Stop if the invariant holds at `node`.
if greater >= v.len() || !is_less(&v[node], &v[greater]) {
if !is_less(&v[node], &v[child]) {
break;
}

// Swap `node` with the greater child, move one step down, and continue sifting.
v.swap(node, greater);
node = greater;
v.swap(node, child);
node = child;
}
};

Expand Down