* @brief Sorts an array using a non-stable quicksort algorithm. * * @param base Pointer to the start of the array. * @param num Number of elements in the array. * @param size Size of each element in bytes. * @param comp Comparison function used to order the elements. */
| 242 | * @param comp Comparison function used to order the elements. |
| 243 | */ |
| 244 | void algorithm_sort(void *base, size_t num, size_t size, CompareFunc comp) { |
| 245 | if (num <= 1 || size == 0 || base == NULL || comp == NULL) { |
| 246 | ALGORITHM_LOG("[algorithm_sort] No sorting needed / invalid arguments."); |
| 247 | return; |
| 248 | } |
| 249 | |
| 250 | ALGORITHM_LOG("[algorithm_sort] Starting introsort for %zu elements.", num); |
| 251 | |
| 252 | /* Two 1-element scratch slots in one allocation: `tmp` for insertion/heap |
| 253 | * moves and `pivot` for the partition pivot value. */ |
| 254 | void *scratch = malloc(size * 2); |
| 255 | if (!scratch) { |
| 256 | ALGORITHM_LOG("[algorithm_sort] Error: scratch allocation failed; array left unmodified."); |
| 257 | return; |
| 258 | } |
| 259 | void *tmp = scratch; |
| 260 | void *pivot = (char *)scratch + size; |
| 261 | |
| 262 | /* Introspection depth limit: 2*floor(log2(num)). Beyond it, heapsort takes |
| 263 | * over to guarantee O(n log n) even on adversarial input. */ |
| 264 | int depth = 0; |
| 265 | for (size_t t = num; t > 1; t >>= 1) { |
| 266 | ++depth; |
| 267 | } |
| 268 | depth *= 2; |
| 269 | |
| 270 | srt_introsort((char *)base, num, size, comp, tmp, pivot, depth); |
| 271 | |
| 272 | free(scratch); |
| 273 | ALGORITHM_LOG("[algorithm_sort] Introsort completed."); |
| 274 | } |
| 275 | |
| 276 | |
| 277 | /** |
no test coverage detected