libc: minimal: add qsort to the minimal libc

This change implements qsort() for the minimal libc via Heapsort.

Heapsort time complexity is O(n log(n)) in the best, average,
and worst cases. It is O(1) in space complexity (i.e. sorts
in-place) and is iterative rather than recursive. Heapsort is
not stable (i.e. does not preserve order of identical elements).

On cortex-m0, this implementation occupies ~240 bytes.

Fixes #28896

Signed-off-by: Christopher Friedt <chrisfriedt@gmail.com>
This commit is contained in:
Christopher Friedt 2021-11-02 06:53:28 -04:00
commit bd83df1552
6 changed files with 122 additions and 203 deletions

View file

@ -257,6 +257,29 @@ static inline void bytecpy(void *dst, const void *src, size_t size)
}
}
/**
* @brief byte by byte swap.
*
* Swap @a size bytes between memory regions @a a and @a b. This is
* guaranteed to be done byte by byte.
*
* @param a Pointer to the the first memory region.
* @param b Pointer to the the second memory region.
* @param size The number of bytes to swap.
*/
static inline void byteswp(void *a, void *b, size_t size)
{
uint8_t t;
uint8_t *aa = (uint8_t *)a;
uint8_t *bb = (uint8_t *)b;
for (; size > 0; --size) {
t = *aa;
*aa++ = *bb;
*bb++ = t;
}
}
/**
* @brief Convert a single character into a hexadecimal nibble.
*