Reputation: 541
I'm new to cython, and I'm trying to write an algorithm that needs to repeatedly sort partially sorted arrays. It appears that python's standard sort (timsort?) is quite good for this, but I haven't figure out how to call this function from inside a cythonized function.
Namely, I want to do something like:
cdef void myfunc(double* y) nogil:
double *y_sort = sort(y)
Any pointers on how to do this would be appreciated.
Upvotes: 2
Views: 2947
Reputation: 6214
Standard C library provides qsort
# from libc.stdlib cimport qsort
# ... declaring "const void *" type seems problematic
# https://stackoverflow.com/questions/8353076/how-do-i-pass-a-pointer-to-a-c-fun$
cdef extern from "stdlib.h":
ctypedef void const_void "const void"
void qsort(void *base, int nmemb, int size,
int(*compar)(const_void *, const_void *)) nogil
cdef int mycmp(const_void * pa, const_void * pb):
cdef double a = (<double *>pa)[0]
cdef double b = (<double *>pb)[0]
if a < b:
return -1
elif a > b:
return 1
else:
return 0
cdef void myfunc(double * y, ssize_t l) nogil:
qsort(y, l, sizeof(double), mycmp)
If the array is "almost-sorted", then insertion sort might be better: https://stackoverflow.com/a/2726841/5781248
Upvotes: 4