57 lines
1.5 KiB
C
57 lines
1.5 KiB
C
#ifndef INCLUDED_C_QUICKSORT_H
|
|||
|
|
#define INCLUDED_C_QUICKSORT_H
|
||
|
|
|
||
|
|
#ifndef INCLUDED_C_TYPES_H
|
||
|
|
#include <c_Types.h>
|
||
|
|
#endif /*INCLUDED_C_TYPES_H*/
|
||
|
|
|
||
|
|
#ifndef INCLUDED_C_MEMORY_H
|
||
|
|
#include <c_Memory.h>
|
||
|
|
#endif /*INCLUDED_C_MEMORY_H*/
|
||
|
|
|
||
|
|
|
||
|
|
/* ------------------------------------------------------------------------------------------------------------------ */
|
||
|
|
/* */
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Recursive partitioning sub-routine.
|
||
|
|
*/
|
||
|
|
|
||
|
|
void c_QuickSortSub(char* arr, long long left, long long right, c_size_t size, void* temp,
|
||
|
|
int (*compar)(const void*, const void*));
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Top-Level Framework Entry Point for Quicksort.
|
||
|
|
* Time Complexity: O(n log n) average | Space Complexity: O(log n) call stack | Stable: No
|
||
|
|
*/
|
||
|
|
C_STATIC_FORCE_INLINE
|
||
|
|
void c_QuickSort(void* base, c_size_t num, c_size_t size,
|
||
|
|
int (*compar)(const void*, const void*)) {
|
||
|
|
if (base == NULL || num < 2 || size == 0) return;
|
||
|
|
|
||
|
|
char* arr = (char*)base;
|
||
|
|
|
||
|
|
// Optimization: Use a local stack buffer if element size fits comfortably
|
||
|
|
#define QSORT_STACK_LIMIT 128
|
||
|
|
char stack_buf[QSORT_STACK_LIMIT];
|
||
|
|
void* temp = NULL;
|
||
|
|
|
||
|
|
if (size <= QSORT_STACK_LIMIT) {
|
||
|
|
temp = stack_buf;
|
||
|
|
} else {
|
||
|
|
temp = C_ALLOC(size);
|
||
|
|
if (temp == NULL) return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Invoke processing across signed range bounds safely
|
||
|
|
c_QuickSortSub(arr, 0, (long long)num - 1, size, temp, compar);
|
||
|
|
|
||
|
|
if (size > QSORT_STACK_LIMIT) {
|
||
|
|
C_FREE(temp);
|
||
|
|
}
|
||
|
|
#undef QSORT_STACK_LIMIT
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
#endif /*INCLUDED_C_QUICKSORT_H*/
|