summaryrefslogtreecommitdiff
path: root/libpsx/src/libc/qsort.c
diff options
context:
space:
mode:
authorXavi Del Campo <xavi.dcr@tutanota.com>2020-01-31 10:32:23 +0100
committerXavi Del Campo <xavi.dcr@tutanota.com>2020-01-31 10:32:23 +0100
commit7c24e9a9b02b04dcaf9507acb94091ea70a2c02d (patch)
treec28d0748652ad4b4222309e46e6cfc82c0906220 /libpsx/src/libc/qsort.c
parenta2b7b6bb1cc2f4a3258b7b2dbc92399d151f864d (diff)
downloadpsxsdk-7c24e9a9b02b04dcaf9507acb94091ea70a2c02d.tar.gz
Imported pristine psxsdk-20190410 from official repo
Diffstat (limited to 'libpsx/src/libc/qsort.c')
-rw-r--r--libpsx/src/libc/qsort.c65
1 files changed, 65 insertions, 0 deletions
diff --git a/libpsx/src/libc/qsort.c b/libpsx/src/libc/qsort.c
new file mode 100644
index 0000000..0cb1d24
--- /dev/null
+++ b/libpsx/src/libc/qsort.c
@@ -0,0 +1,65 @@
+// quickSort
+//
+// This public-domain C implementation by Darel Rex Finley.
+//
+// Modified by Giuseppe Gatta
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
+{
+ #define QSORT_MAX_LEVELS 300
+
+
+ int beg[QSORT_MAX_LEVELS], end[QSORT_MAX_LEVELS], i=0, L, R, swap ;
+ char piv[size];
+
+ beg[0]=0; end[0]=nmemb;
+
+ while (i>=0)
+ {
+ L=beg[i]; R=end[i]-1;
+
+ if (L<R)
+ {
+ memcpy(piv, base + (size * L), size);
+
+ while (L<R)
+ {
+ while(compar(base + (R*size), piv) > 0 && L<R) R--;
+
+ if (L<R)
+ {
+ memcpy(base + (size *L), base + (size * R), size);
+ L++;
+ }
+
+ while(compar(base + (L*size), piv) <= 0 && L<R) L++;
+
+ if (L<R)
+ {
+ memcpy(base + (size *R), base + (size * L), size);
+ R--;
+ }
+ }
+
+ memcpy(base + (size*L), piv, size);
+
+ beg[i+1]=L+1;
+ end[i+1]=end[i];
+ end[i++]=L;
+
+ if (end[i]-beg[i]>end[i-1]-beg[i-1])
+ {
+ swap=beg[i]; beg[i]=beg[i-1]; beg[i-1]=swap;
+ swap=end[i]; end[i]=end[i-1]; end[i-1]=swap;
+ }
+ }
+ else
+ {
+ i--;
+ }
+ }
+}