AquilaOS documentation
How it works, and its code
Loading...
Searching...
No Matches
qsort.h
Go to the documentation of this file.
1#ifndef _QSORT_H
2#define _QSORT_H
3
4#include <core/system.h>
5#include <core/string.h>
6
7/* Sorting an array, as the C library's qsort() does. */
8
10static inline void __qsort_swap(char *a, char *b, size_t size)
11{
12 char t;
13 while (size--) {
14 t = *a;
15 *a = *b;
16 *b = t;
17 ++a; ++b;
18 }
19}
20
23static inline void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *))
24{
25 if (nmemb <= 1 || size == 0) return;
26
27 void *pivot = (char *) base + (nmemb - 1) * size;
28 void *cur = base;
29 void *wall = base;
30
31 for (size_t i = 0; i < nmemb - 1; ++i) {
32 if (compar(cur, pivot) < 0) {
33 __qsort_swap(cur, wall, size);
34 wall = (char *) wall + size;
35 }
36 cur = (char *) cur + size;
37 }
38
39 __qsort_swap(wall, pivot, size);
40
41 size_t idx = ((char *) wall - (char *) base) / size;
42
43 qsort(base, idx, size, compar);
44 qsort((char *) wall + size, nmemb - idx - 1, size, compar);
45}
46
47#endif /* ! _QSORT_H */
static void __qsort_swap(char *a, char *b, size_t size)
Swaps two elements of size bytes.
Definition qsort.h:10
static void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *))
Sorts an array of nmemb elements of size bytes, in the order compar says, with quicksort (the last el...
Definition qsort.h:23