|
@@ -1,7 +1,7 @@
|
|
|
/*
|
|
|
* algorithm.c
|
|
|
*
|
|
|
- * Copyright (C) 2017 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
|
|
|
+ * Copyright (C) 2019 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
|
|
|
*
|
|
|
* This program is free software: you can redistribute it and/or modify
|
|
|
* it under the terms of the GNU Affero General Public License as
|
|
@@ -22,26 +22,25 @@
|
|
|
|
|
|
void __CRT_PUBLIC(qsort)(void *base, size_t nmemb, size_t size, int (*compare)(const void*, const void*))
|
|
|
{
|
|
|
- void *pivot = (void*)((uintptr_t)base + (nmemb / 2) * size);
|
|
|
- void *temp = __builtin_alloca(size);
|
|
|
- if (nmemb <= 1) return;
|
|
|
+ char *bytes = base, pivot[size], temp[size];
|
|
|
+ ptrdiff_t low = 0, high = nmemb - 1;
|
|
|
|
|
|
- size_t low = 0;
|
|
|
- size_t high = nmemb - 1;
|
|
|
+ if (nmemb <= 1) return;
|
|
|
+ __builtin_memcpy(pivot, &bytes[(nmemb / 2 - 1) * size], size);
|
|
|
|
|
|
for (;;)
|
|
|
{
|
|
|
- while (compare((void*)((uintptr_t)base + low * size), pivot) < 0) low++;
|
|
|
- while (compare((void*)((uintptr_t)base + high * size), pivot) > 0) high--;
|
|
|
+ while (compare(&bytes[low * size], pivot) < 0) low++;
|
|
|
+ while (compare(&bytes[high * size], pivot) > 0) high--;
|
|
|
if (low >= high) break;
|
|
|
|
|
|
- __builtin_memcpy(temp, (void*)((uintptr_t)base + low * size), size);
|
|
|
- __builtin_memcpy((void*)((uintptr_t)base + low * size), (void*)((uintptr_t)base + high * size), size);
|
|
|
- __builtin_memcpy((void*)((uintptr_t)base + high * size), temp, size);
|
|
|
+ __builtin_memcpy(temp, &bytes[low * size], size);
|
|
|
+ __builtin_memcpy(&bytes[low * size], &bytes[high * size], size);
|
|
|
+ __builtin_memcpy(&bytes[high * size], temp, size);
|
|
|
}
|
|
|
|
|
|
- __CRT_PUBLIC(qsort)(base, high, size, compare);
|
|
|
- __CRT_PUBLIC(qsort)((void*)((size_t)base + high * size), nmemb - high, size, compare);
|
|
|
+ __CRT_PUBLIC(qsort)(bytes, high + 1, size, compare);
|
|
|
+ __CRT_PUBLIC(qsort)(&bytes[(high + 1) * size], nmemb - (high + 1), size, compare);
|
|
|
}
|
|
|
|
|
|
void *__CRT_PUBLIC(bsearch)(const void *key, const void *base, size_t nmemb, size_t size, int (*compare)(const void*, const void*))
|