Tony Babarino
Tony Babarino

Reputation: 3405

Cython memoryviews error: Invalid index for memoryview specified

I'm trying to implement standard quicksort in cython using memoryviews. Here is my code:

def quicksort_cython(double[:] l):
    _quicksort(l, 0, len(l) - 1)


cdef void _quicksort(double[:] l, double start, double stop):
    cdef double pivot, left, right, tmp
    if stop - start > 0:
        pivot = l[start]
        left = start
        right = stop
        while left <= right:
            while l[left] < pivot:
                left += 1
            while l[right] > pivot:
                right -= 1
            if left <= right:
                tmp = l[left]
                l[left] = l[right]
                l[right] = tmp
                left += 1
                right -= 1
        _quicksort(l, start, right)
        _quicksort(l, left, stop)

However, during the compilation with standard setup.py file and python setup.py build_ext --inplace command I get multiple errors regarding the memoryview access:

Error compiling Cython file:
------------------------------------------------------------
...


cdef void _quicksort(double[:] l, double start, double stop):
    cdef double pivot, left, right, tmp
    if stop - start > 0:
        pivot = l[start]
                      ^
------------------------------------------------------------

quicksort_cython_opt3.pyx:9:23: Invalid index for memoryview specified

Can someone tell me what am I doing wrong? Also any performance improving tips will be appreciated as I'm new to Cython.. Thanks!

Upvotes: 1

Views: 1088

Answers (1)

Matt Messersmith
Matt Messersmith

Reputation: 13747

Typically doubles can't be indices (should be ints). I assume that's the problem...although I'm admittedly not familiar with cython memoryviews.

Upvotes: 2

Related Questions