authorgravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2019-12-04 16:41:32+01:00
committergravatar for robin@voetter.nlRobin Voetter <robin@voetter.nl> 2019-12-04 16:41:32+01:00
log6bb0ee0bc4015823091112eade0440a5ca9e84c2
tree082b6bb4a851bdf119021b97872ca904c11ce9ff
parent38791ac616069963fd808ec724161b93cbc564c1

Add std.sort.isSorted


1 files changed, 38 insertions(+), 0 deletions(-)

lib/std/sort.zig+38
......@@ -1210,3 +1210,41 @@ pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T {
12101210 }
12111211 return biggest;
12121212}
1213
1214pub fn isSorted(comptime T: type, items: []const T, lessThan: fn (lhs: T, rhs: T) bool) bool {
1215 var i: usize = 1;
1216 while (i < items.len) : (i += 1) {
1217 if (lessThan(items[i], items[i - 1])) {
1218 return false;
1219 }
1220 }
1221
1222 return true;
1223}
1224
1225test "std.sort.isSorted" {
1226 testing.expect(isSorted(i32, &[_]i32{}, asc(i32)));
1227 testing.expect(isSorted(i32, &[_]i32{10}, asc(i32)));
1228 testing.expect(isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, asc(i32)));
1229 testing.expect(isSorted(i32, &[_]i32{ -10, 1, 1, 1, 10 }, asc(i32)));
1230
1231 testing.expect(isSorted(i32, &[_]i32{}, desc(i32)));
1232 testing.expect(isSorted(i32, &[_]i32{-20}, desc(i32)));
1233 testing.expect(isSorted(i32, &[_]i32{ 3, 2, 1, 0, -1 }, desc(i32)));
1234 testing.expect(isSorted(i32, &[_]i32{ 10, -10 }, desc(i32)));
1235
1236 testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, asc(i32)));
1237 testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, desc(i32)));
1238
1239 testing.expectEqual(false, isSorted(i32, &[_]i32{ 5, 4, 3, 2, 1 }, asc(i32)));
1240 testing.expectEqual(false, isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, desc(i32)));
1241
1242 testing.expect(isSorted(u8, "abcd", asc(u8)));
1243 testing.expect(isSorted(u8, "zyxw", desc(u8)));
1244
1245 testing.expectEqual(false, isSorted(u8, "abcd", desc(u8)));
1246 testing.expectEqual(false, isSorted(u8, "zyxw", asc(u8)));
1247
1248 testing.expect(isSorted(u8, "ffff", asc(u8)));
1249 testing.expect(isSorted(u8, "ffff", desc(u8)));
1250}