diff --git a/inc/stdlib.h b/inc/stdlib.h index 3bf4470..7833aa4 100644 --- a/inc/stdlib.h +++ b/inc/stdlib.h @@ -85,8 +85,20 @@ int at_quick_exit(void (*func)(void)); char *getenv (const char *name); int system (const char *string); -const void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); -// void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)); +const void *bsearch( + const void *key, + const void *base, + size_t nmemb, + size_t size, + int (*compar)(const void *, const void *) +); + +void qsort( + void *base, + size_t nmemb, + size_t size, + int (*compar)(const void *, const void *) +); // Multibyte strings // int mblen(const char *s, size_t n); diff --git a/src/code/stdlib/algorithm.c b/src/code/stdlib/algorithm.c index c853f49..2c6647b 100644 --- a/src/code/stdlib/algorithm.c +++ b/src/code/stdlib/algorithm.c @@ -36,7 +36,13 @@ lldiv_t lldiv(long long x, long long y) { return res; } -const void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)) { +const void *bsearch( + const void *key, + const void *base, + size_t nmemb, + size_t size, + int (*compar)(const void *, const void *) +) { size_t left = 0; size_t right = nmemb; @@ -52,3 +58,26 @@ const void *bsearch(const void *key, const void *base, size_t nmemb, size_t size return NULL; } + +void qsort( + void *base, + size_t nmemb, + size_t size, + int (*diff)(const void *, const void *) +) { + // Ima be doing bublbe sort for now + char *bytes = base; + for(size_t i = 0; i != nmemb-1; ++i) { + for(size_t j = 0; j < nmemb-i-1; ++j) { + char *this = bytes+j*size; + char *that = this+size; + if(diff(this, that) > 0) { + for(size_t b=0;b!=size;++b) { + char temp = this[b]; + this[b] = that[b]; + that[b] = temp; + } + } + } + } +} diff --git a/test/test_qsort.c b/test/test_qsort.c new file mode 100644 index 0000000..1a49d99 --- /dev/null +++ b/test/test_qsort.c @@ -0,0 +1,34 @@ + +#include +#include + +int compare_ints(const void *p, const void *q) { + int x = *(const int *)p; + int y = *(const int *)q; + + /* Avoid return x - y, which can cause undefined behaviour + because of signed integer overflow. */ + if (x < y) + return -1; // Return -1 if you want ascending, 1 if you want descending order. + else if (x > y) + return 1; // Return 1 if you want ascending, -1 if you want descending order. + + return 0; + // All the logic is often alternatively written: + return (x > y) - (x < y); +} + +/* Sort an array of n integers, pointed to by a. */ +void sort_ints(int *a, size_t n) { + qsort(a, n, sizeof(*a), compare_ints); +} + +int main() { + int arr[] = {-1,10,155, 256-10,0,0,0}; + int count = sizeof arr / sizeof *arr; + sort_ints(arr, count); + for(int i = 0; i != count; ++i) { + printf("%d\t", arr[i]); + } +} +