diff options
| author | zhangyunhao <zhangyunhao116@gmail.com> | 2022-06-20 08:30:27 +0000 |
|---|---|---|
| committer | zhangyunhao <zhangyunhao116@gmail.com> | 2022-06-20 08:30:27 +0000 |
| commit | 98507f202d9de65aace038eeb6fffa45e3c3dfd8 (patch) | |
| tree | 76dd5372bac19ad10ce1eabc1dccc21e48f99389 | |
| parent | ecd44958e0a21110d09862ee080d95a4ca6c52f8 (diff) | |
| download | rust-98507f202d9de65aace038eeb6fffa45e3c3dfd8.tar.gz rust-98507f202d9de65aace038eeb6fffa45e3c3dfd8.zip | |
Optimize heapsort
| -rw-r--r-- | library/core/src/slice/sort.rs | 19 |
1 files changed, 11 insertions, 8 deletions
diff --git a/library/core/src/slice/sort.rs b/library/core/src/slice/sort.rs index 1f392a07971..6a201834b8e 100644 --- a/library/core/src/slice/sort.rs +++ b/library/core/src/slice/sort.rs @@ -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; } }; |
