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.
numpyis not a good way to learnnumpy. Superficial similarities can lead to bugs like this, and also promote poornumpystyle.