Skip to content

Commit 5750a6a

Browse files
committed
Auto merge of rust-lang#93765 - zhangyunhao116:heapsort, r=m-ou-se
Optimize heapsort The new implementation is about 10% faster than the previous one(sorting random 1000 items).
2 parents b12708f + 98507f2 commit 5750a6a

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

library/core/src/slice/sort.rs

+11-8
Original file line numberDiff line numberDiff line change
@@ -188,22 +188,25 @@ where
188188
// This binary heap respects the invariant `parent >= child`.
189189
let mut sift_down = |v: &mut [T], mut node| {
190190
loop {
191-
// Children of `node`:
192-
let left = 2 * node + 1;
193-
let right = 2 * node + 2;
191+
// Children of `node`.
192+
let mut child = 2 * node + 1;
193+
if child >= v.len() {
194+
break;
195+
}
194196

195197
// Choose the greater child.
196-
let greater =
197-
if right < v.len() && is_less(&v[left], &v[right]) { right } else { left };
198+
if child + 1 < v.len() && is_less(&v[child], &v[child + 1]) {
199+
child += 1;
200+
}
198201

199202
// Stop if the invariant holds at `node`.
200-
if greater >= v.len() || !is_less(&v[node], &v[greater]) {
203+
if !is_less(&v[node], &v[child]) {
201204
break;
202205
}
203206

204207
// Swap `node` with the greater child, move one step down, and continue sifting.
205-
v.swap(node, greater);
206-
node = greater;
208+
v.swap(node, child);
209+
node = child;
207210
}
208211
};
209212

0 commit comments

Comments
 (0)