commit f1688232e5fdf72bb19fd201f08f2dac17c72ad1
parent 3a500c8292e08abc12f8f0cea4506aaa27b4c91c
Author: Pierre Curto <pierre.curto@gmail.com>
Date: Thu, 6 Oct 2022 10:03:51 +0200
sort::sorted: fix invalid results and add tests
Signed-off-by: Pierre Curto <pierre.curto@gmail.com>
Diffstat:
2 files changed, 14 insertions(+), 2 deletions(-)
diff --git a/sort/+test.ha b/sort/+test.ha
@@ -59,4 +59,15 @@
for (let i = 1z; i < len(nums); i += 1) {
assert(nums[i] >= nums[i - 1]);
};
+
+};
+
+@test fn sorted() void = {
+ let nums = [1, 3, 2];
+
+ assert(!sorted(nums, size(int), &icmp));
+
+ sort(nums, size(int), &icmp);
+ assert(sorted(nums, size(int), &icmp));
+ assert(sorted(nums[..0], size(int), &icmp));
};
diff --git a/sort/sort.ha b/sort/sort.ha
@@ -22,8 +22,9 @@ export fn strings(items: []str) void = sort(items, size(str), &scmp);
// Checks if all of the items in a slice are sorted.
export fn sorted(items: []void, itemsz: size, cmp: *cmpfunc) bool = {
- for (let i = 0z; i < len(items) - 1; i += 1) {
- if (cmp(&items[i], &items[i + 1]) > 0) {
+ let ba = items: *[*]u8;
+ for (let i = 1z; i < len(items); i += 1) {
+ if (cmp(&ba[(i - 1) * itemsz], &ba[i * itemsz]) > 0) {
return false;
};
};