aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRobin Voetter <robin@voetter.nl>2019-12-04 16:42:18 +0100
committerRobin Voetter <robin@voetter.nl>2019-12-04 16:42:18 +0100
commit65f57e44993c51ae6a582d18ad7c460ac229e68f (patch)
tree02c761ba2ab9e54755746f0952b5400f77d71491
parent6bb0ee0bc4015823091112eade0440a5ca9e84c2 (diff)
downloadzig-65f57e44993c51ae6a582d18ad7c460ac229e68f.tar.gz
zig-65f57e44993c51ae6a582d18ad7c460ac229e68f.zip
Make std.sort.max accept const slices and add tests
-rw-r--r--lib/std/sort.zig22
1 files changed, 20 insertions, 2 deletions
diff --git a/lib/std/sort.zig b/lib/std/sort.zig
index 0fb029bb51..4913fd8f78 100644
--- a/lib/std/sort.zig
+++ b/lib/std/sort.zig
@@ -1189,7 +1189,7 @@ fn fuzzTest(rng: *std.rand.Random) void {
}
}
-pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
+pub fn min(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) T {
var i: usize = 0;
var smallest = items[0];
for (items[1..]) |item| {
@@ -1200,7 +1200,16 @@ pub fn min(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
return smallest;
}
-pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
+test "std.sort.min" {
+ testing.expectEqual(@as(i32, 1), min(i32, &[_]i32{1}, asc(i32)));
+ testing.expectEqual(@as(i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
+ testing.expectEqual(@as(i32, 2), min(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
+ testing.expectEqual(@as(i32, 1), min(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
+ testing.expectEqual(@as(i32, -10), min(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
+ testing.expectEqual(@as(i32, 7), min(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
+}
+
+pub fn max(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) T {
var i: usize = 0;
var biggest = items[0];
for (items[1..]) |item| {
@@ -1211,6 +1220,15 @@ pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
return biggest;
}
+test "std.sort.max" {
+ testing.expectEqual(@as(i32, 1), max(i32, &[_]i32{1}, asc(i32)));
+ testing.expectEqual(@as(i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
+ testing.expectEqual(@as(i32, 9), max(i32, &[_]i32{ 9, 3, 8, 2, 5 }, asc(i32)));
+ testing.expectEqual(@as(i32, 1), max(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
+ testing.expectEqual(@as(i32, 10), max(i32, &[_]i32{ -10, 1, 10 }, asc(i32)));
+ testing.expectEqual(@as(i32, 3), max(i32, &[_]i32{ 6, 3, 5, 7, 6 }, desc(i32)));
+}
+
pub fn isSorted(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) bool {
var i: usize = 1;
while (i < items.len) : (i += 1) {