Skip to content

Commit 1435604

Browse files
committedDec 19, 2017
add sort.min and sort.max functions to stdlib
·
0.15.20.2.0
1 parent 2a8160e commit 1435604

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed
 

‎std/mem.zig‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -511,9 +511,8 @@ fn testWriteIntImpl() {
511511

512512
pub fn min(comptime T: type, slice: []const T) -> T {
513513
var best = slice[0];
514-
var i: usize = 1;
515-
while (i < slice.len) : (i += 1) {
516-
best = math.min(best, slice[i]);
514+
for (slice[1..]) |item| {
515+
best = math.min(best, item);
517516
}
518517
return best;
519518
}
@@ -524,9 +523,8 @@ test "mem.min" {
524523

525524
pub fn max(comptime T: type, slice: []const T) -> T {
526525
var best = slice[0];
527-
var i: usize = 1;
528-
while (i < slice.len) : (i += 1) {
529-
best = math.max(best, slice[i]);
526+
for (slice[1..]) |item| {
527+
best = math.max(best, item);
530528
}
531529
return best;
532530
}

‎std/sort.zig‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1132,3 +1132,25 @@ fn fuzzTest(rng: &std.rand.Rand) {
11321132
}
11331133
}
11341134
}
1135+
1136+
pub fn min(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)->bool) -> T {
1137+
var i: usize = 0;
1138+
var smallest = items[0];
1139+
for (items[1..]) |item| {
1140+
if (lessThan(item, smallest)) {
1141+
smallest = item;
1142+
}
1143+
}
1144+
return smallest;
1145+
}
1146+
1147+
pub fn max(comptime T: type, items: []T, lessThan: fn(lhs: &const T, rhs: &const T)->bool) -> T {
1148+
var i: usize = 0;
1149+
var biggest = items[0];
1150+
for (items[1..]) |item| {
1151+
if (lessThan(biggest, item)) {
1152+
biggest = item;
1153+
}
1154+
}
1155+
return biggest;
1156+
}

0 commit comments

Comments
 (0)
Please sign in to comment.