summaryrefslogtreecommitdiff
path: root/userland/libc/stdlib/qsort.c
diff options
context:
space:
mode:
authorAnton Kling <anton@kling.gg>2023-10-22 19:50:38 +0200
committerAnton Kling <anton@kling.gg>2023-10-22 19:50:38 +0200
commit4e09bca9e34c226b6d7e34b4fa11248405fd988e (patch)
tree80f156b7940d9d19971395f335530170c69516c7 /userland/libc/stdlib/qsort.c
Move everything into a new repo.
Diffstat (limited to 'userland/libc/stdlib/qsort.c')
-rw-r--r--userland/libc/stdlib/qsort.c29
1 files changed, 29 insertions, 0 deletions
diff --git a/userland/libc/stdlib/qsort.c b/userland/libc/stdlib/qsort.c
new file mode 100644
index 0000000..3f87db5
--- /dev/null
+++ b/userland/libc/stdlib/qsort.c
@@ -0,0 +1,29 @@
+#include <stdlib.h>
+#include <string.h>
+
+// https://pubs.opengroup.org/onlinepubs/9699919799/functions/qsort.html
+void qsort(void *base, size_t nel, size_t width,
+ int (*compar)(const void *, const void *)) {
+ // If the nel argument has the value zero, the comparison function pointed to
+ // by compar shall not be called and no rearrangement shall take place.
+ if (0 == nel)
+ return;
+
+ // AB
+ // Results in negative
+ // BA
+ // Results in positive
+
+ // Using bubblesort
+ unsigned char *p = base;
+ for (size_t i = 1; i < nel; i++) {
+ for (size_t j = 0; j < nel; j++) {
+ if (compar((p + i * width), (p + j * width)) < 0) {
+ unsigned char tmp[width];
+ memcpy(tmp, (p + i * width), width);
+ memcpy((p + i * width), (p + j * width), width);
+ memcpy((p + j * width), tmp, width);
+ }
+ }
+ }
+}