2

I am attempting to quicksort a list and want to do so in place.

I have the following code and want to know in general (this problem comes up often for me as I try to solve list problems in place on the actual list rather than a complicated sequence of returns or using weird indices) can a list slice ever allow me to affect the list from which it's derived? Are there larger ramifications for doing something like this?

def partition(A,l,r):
    p=A[l]
    i=l+1
    print(A)
    for j in range(l+1,r):
        if A[j]<p:
            save=A[i]
            A[i]=A[j]
            A[j]=save
            i+=1
    save=A[i-1]
    A[i-1]=A[l]
    A[l]=save
    return i-1
def quickSort(A,n):
    if n>1:
        split=partition(A,0,n)
        quickSort(A[:split],len(A[:split]))
        quickSort(A[split+1:],len(A[split+1:]))
        print(A)
    return A
A=[3,4,5,2,10,7,6,9,1]
print(quickSort(A,len(A)))
Chris L.
  • 43
  • 7

1 Answers1

4

numpy lets you assign to slices in a way that is reflected in the original array (numpy slices return views):

import numpy as np

a = np.array(range(10))
print(a)   # [0 1 2 3 4 5 6 7 8 9]
b = a[3:7]
print(b)   # [3 4 5 6]
b[0] = 33
print(b)   # [33  4  5  6]
print(a)   # [ 0  1  2 33  4  5  6  7  8  9]

a slice of a python list always returns a copy so you would have to write a view on a list yourself...

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Man you are awesome! works perfectly and I would have never thought of using numpy for a task like this. Thank you thank you thank you. – Chris L. Feb 07 '17 at 10:42