This commit is contained in:
blueloveTH 2024-07-07 15:53:25 +08:00
parent 22ae57fc9b
commit 5f98f916a9
2 changed files with 8 additions and 9 deletions

View File

@ -2,16 +2,15 @@
#include <string.h>
#include <stdlib.h>
static bool merge(char* a_begin,
static bool merge(char* a,
char* a_end,
char* b_begin,
char* b,
char* b_end,
char* res,
char* r,
int elem_size,
int (*f_le)(const void* a, const void* b)) {
char *a = a_begin, *b = b_begin, *r = res;
int (*f_lt)(const void* a, const void* b)) {
while(a < a_end && b < b_end) {
int res = f_le(a, b);
int res = f_lt(a, b);
// check error
if(res == -1) return false;
if(res) {
@ -35,14 +34,14 @@ static bool merge(char* a_begin,
bool c11__stable_sort(void* ptr_,
int count,
int elem_size,
int (*f_le)(const void* a, const void* b)) {
int (*f_lt)(const void* a, const void* b)) {
// merge sort
char *ptr = ptr_, *tmp = malloc(count * elem_size);
for(int seg = 1; seg < count; seg *= 2) {
for(char* a = ptr; a < ptr + (count - seg) * elem_size; a += 2 * seg * elem_size) {
char *b = a + seg * elem_size, *a_end = b, *b_end = b + seg * elem_size;
if(b_end > ptr + count * elem_size) b_end = ptr + count * elem_size;
bool ok = merge(a, a_end, b, b_end, tmp, elem_size, f_le);
bool ok = merge(a, a_end, b, b_end, tmp, elem_size, f_lt);
if(!ok) {
free(tmp);
return false;

View File

@ -322,7 +322,7 @@ static bool _py_list__insert(int argc, py_Ref argv) {
static bool _py_list__sort(int argc, py_Ref argv) {
PY_CHECK_ARGC(1);
List* self = py_touserdata(py_arg(0));
c11__stable_sort(self->data, self->count, sizeof(py_TValue), (int (*)(const void*, const void*))py_le);
c11__stable_sort(self->data, self->count, sizeof(py_TValue), (int (*)(const void*, const void*))py_lt);
py_newnone(py_retval());
return true;
}