1

I wanted to do a little numpy practice, so I decided to borrow some quicksort code and change it to use numpy.

This is the original:

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]

    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]

    return quicksort(left) + middle + quicksort(right)

print (quicksort([1,2,32,121,4,5,51]))

And here I change it to use numpy arrays

def quicksort_np(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]

    left = arr[arr < pivot]
    middle = arr[arr == pivot]
    right = arr[arr > pivot]

    return quicksort_np(left) + middle + quicksort_np(right)

print (quicksort_np(np.array([1,2,32,121,4,5,51])))

Running the original version, I get the correct output:

[1, 2, 4, 5, 32, 51, 121]

However, running the numpy version, I get an empty list:

[]

I can't understand what the problem is. I thought it had to do with the new lists not being copies, so I tried calling .copy() on each list inside quicksort_np, but I still got the same output.

1
  • Porting list code to numpy is not a good way to learn numpy. Superficial similarities can lead to bugs like this, and also promote poor numpy style. Commented Jan 23, 2018 at 3:56

2 Answers 2

2

I think the error is in your line:

return quicksort_np(left) + middle + quicksort_np(right)

The '+' operator is a concatenation operator for python lists, but a sum operator for numpy arrays.

You can probably solve the problem by using np.concatenate

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much. I guess I have to be careful of what I assume is common across python and numpy
2

The + operator works on python lists but not on numpy arrays.

Try np.hstack instead:

def quicksort_np(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]

    left = arr[arr < pivot]
    middle = arr[arr == pivot]
    right = arr[arr > pivot]

    return np.hstack((quicksort_np(left), middle, quicksort_np(right)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.