0

I tried to implement the counting sort from Cormen Book but python does something strange with the original list while changing the value of B which is suposed to be the output array

def counting_sort(A):

    A[0:0]=[0]
    C=[]
    B=A
    for i in range(max(A)+1):
        C.append(0);
    for j in range(1,len(A)):
        C[A[j]]=C[A[j]]+1
    for k in range(1,len(C)):
        C[k]=C[k]+C[k-1]
    print(C)
    for l in range(len(A)-1,0,-1):
        B[C[A[l]]]=A[l]
        C[A[l]]= C[A[l]]-1
        print(a)
        print(C)
    B.pop(0)
    return B
A=[3,5,6,0,2,9,1,8,2]

print(counting_sort(A))
jpp
  • 159,742
  • 34
  • 281
  • 339
  • Please define precisely `counting sort from Cormen Book` [in your question](https://stackoverflow.com/posts/52156764/edit). – jpp Sep 03 '18 at 22:31
  • 1
    `B=A` makes the variable `B` refer to the *same object* as variable `A`, so *any* mutations on that object will be visible from `A` *and* `B`. Furthermore, you mutate the list you pass into your function here: `A[0:0]=[0]` so... – juanpa.arrivillaga Sep 03 '18 at 22:33

0 Answers0