Skip to content

Commit 45e07bd

Browse files
committed
Break out early if the target is in partitionEqual
1 parent 05710a4 commit 45e07bd

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

lib/std/select.zig

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ pub fn nthElementContext(n: usize, a: usize, b: usize, context: anytype) void {
7272
assert(a < b);
7373
const len = b - a;
7474
assert(n < len);
75+
const target = a + n;
7576
var left: usize = a;
7677
var right: usize = b;
7778
var depth_limit: usize = math.log2_int(usize, len) * 2; // This is what C++ std::nth_element does.
@@ -81,7 +82,7 @@ pub fn nthElementContext(n: usize, a: usize, b: usize, context: anytype) void {
8182
break;
8283
}
8384
if (depth_limit == 0) {
84-
heapSelectContext(n - (left - a), left, right, context);
85+
heapSelectContext(target - left, left, right, context);
8586
break;
8687
}
8788
depth_limit -= 1;
@@ -92,10 +93,10 @@ pub fn nthElementContext(n: usize, a: usize, b: usize, context: anytype) void {
9293
// This case is usually hit when the slice contains many duplicate elements.
9394
if (left > a and !context.lessThan(left - 1, pivot)) {
9495
left = sort.partitionEqual(left, right, pivot, context);
96+
if (target < left) break;
9597
continue;
9698
}
9799
_ = sort.partition(left, right, &pivot, context);
98-
const target = a + n;
99100
if (pivot == target) {
100101
break;
101102
} else if (pivot > target) {

0 commit comments

Comments
 (0)