authorgravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2019-12-04 16:42:18+01:00
committergravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2019-12-04 16:42:18+01:00
log65f57e44993c51ae6a582d18ad7c460ac229e68f
tree02c761ba2ab9e54755746f0952b5400f77d71491
parent6bb0ee0bc4015823091112eade0440a5ca9e84c2

Make std.sort.max accept const slices and add tests


1 files changed, 20 insertions(+), 2 deletions(-)

lib/std/sort.zig+20-2
......@@ -1189,7 +1189,7 @@ fn fuzzTest(rng: *std.rand.Random) void {
11891189 }
11901190}
11911191
1192pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
1192pub fn min(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) T {
11931193 var i: usize = 0;
11941194 var smallest = items[0];
11951195 for (items[1..]) |item| {
......@@ -1200,7 +1200,16 @@ pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
12001200 return smallest;
12011201}
12021202
1203pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
1203test "std.sort.min" {
1204 testing.expectEqual(@as(i32, 1), min(i32, &[_]i32{1}, asc(i32)));
1205 testing.expectEqual(@as(i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1206 testing.expectEqual(@as(i32, 2), min(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
1207 testing.expectEqual(@as(i32, 1), min(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1208 testing.expectEqual(@as(i32, -10), min(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
1209 testing.expectEqual(@as(i32, 7), min(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
1210}
1211
1212pub fn max(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) T {
12041213 var i: usize = 0;
12051214 var biggest = items[0];
12061215 for (items[1..]) |item| {
......@@ -1211,6 +1220,15 @@ pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
12111220 return biggest;
12121221}
12131222
1223test "std.sort.max" {
1224 testing.expectEqual(@as(i32, 1), max(i32, &[_]i32{1}, asc(i32)));
1225 testing.expectEqual(@as(i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1226 testing.expectEqual(@as(i32, 9), max(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
1227 testing.expectEqual(@as(i32, 1), max(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1228 testing.expectEqual(@as(i32, 10), max(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
1229 testing.expectEqual(@as(i32, 3), max(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
1230}
1231
12141232pub fn isSorted(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) bool {
12151233 var i: usize = 1;
12161234 while (i < items.len) : (i += 1) {