| ... | @@ -1210,3 +1210,41 @@ pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T { | ... | @@ -1210,3 +1210,41 @@ pub fn max(comptime T: type, items: []T, lessThan: fn (lhs: T, rhs: T) bool) T { |
| 1210 | } | 1210 | } |
| 1211 | return biggest; | 1211 | return biggest; |
| 1212 | } | 1212 | } |
| | 1213 | |
| | 1214 | pub 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 | |
| | 1225 | test "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 | } |