stdlib.h: qsort (slow)

This commit is contained in:
bumbread 2022-06-27 13:40:19 +11:00
parent d232486a11
commit f068e506c7
3 changed files with 78 additions and 3 deletions

View File

@ -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);

View File

@ -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;
}
}
}
}
}

34
test/test_qsort.c Normal file
View File

@ -0,0 +1,34 @@
#include <stdlib.h>
#include <stdio.h>
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]);
}
}