Skip to content

Commit

Permalink
Merge pull request #47 from Kray-G/feature/issue#17/add-stdlibc
Browse files Browse the repository at this point in the history
fixed #17: added stdlibc
  • Loading branch information
Kray-G authored Nov 12, 2019
2 parents 8252234 + bf0fe55 commit 4fbcf54
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
38 changes: 38 additions & 0 deletions kccrt/libsrc/stdlib.c
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,42 @@ int rand(void)
return (unsigned)(__kcc_rand_seed / 65536L) % (RAND_MAX+1);
}

#define SWAP(x, y, size) \
do { \
size_t s = (size); \
char *a = (x), *b = (y); \
do { \
char t = *a; \
*a++ = *b; \
*b++ = t; \
} while (--s > 0); \
} while (0) \
/**/

#define KCCQ(a, i) ((char *)a + (i) * size)

void __quicksort(int first, int last, void *base, size_t size, int (*comp)(const void *, const void *))
{
int i, j;
void *x = KCCQ(base, (first + last) / 2);
i = first; j = last;
for ( ; ; ) {
while (comp(x, KCCQ(base, i)) > 0) i++;
while (comp(KCCQ(base, j), x) > 0) j--;
if (i >= j) break;
SWAP(KCCQ(base,i), KCCQ(base,j), size);
i++;
j--;
}
if (first < i - 1) __quicksort(first , i - 1, base, size, comp);
if (j + 1 < last) __quicksort(j + 1, last, base, size, comp);
}

#undef KCCQ

void qsort(void *base, size_t n, size_t size, int (*comp)(const void *, const void *))
{
__quicksort(0, n - 1, base, size, comp);
}

#endif
27 changes: 27 additions & 0 deletions samples/qsort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <stdio.h>
#include <stdlib.h>

int cmp(const void *p, const void *q)
{
return *(int*)p - *(int*)q;
}

#define N 20
int a[N];

int main(void)
{
int i;

printf("Before:");
for (i = 0; i < N; i++) {
a[i] = rand() / (RAND_MAX / 100 + 1);
printf(" %2d", a[i]);
}
printf("\n");
qsort(a, sizeof(a)/sizeof(a[0]), sizeof(a[0]), cmp);
printf("After: ");
for (i = 0; i < N; i++) printf(" %2d", a[i]);
printf("\n");
return 0;
}

0 comments on commit 4fbcf54

Please sign in to comment.