Quicksort non recursive

806 views Asked by At

The statement says:

Write a nonrecursive (negative) function which given a list of integers (possibly disordered) function returns the same list with negative numbers to positive head and back (regardless of the order between them). This algorithm can be solved in the form requested a similar strategy (though a bit more simple) partition in quicksort.

I put this code:

def negatius(a):

    fin = len(a) - 1
    i = 0
    b = [i]

    for i in range(len(a)):
        if a[i] < 0:
            b[fin] = a[i]
            i += 1

        else:
            b[fin] = a[i]
            fin += 1

    print "La llista és",b[fin]


a=[1,-2,3,-4,-3,5,6]
negatius(a)

And appears an error: local variable 'i' referenced before assignment. I dont understand this

1

There are 1 answers

2
vikingosegundo On

You are incrementing fin from the highest index on, and use it to access elements in lists with this index. that can't be right, as these indices do not exist.

b[fin] = a[i]

and

b[fin] = a[i]
fin += 1

and

print "La llista és",b[fin]

Also in if and else you are append to the list. That doenst make much sense too. You should append once and prepend in the other case

def negatius(a):
    fin = len(a) - 1
    i = 0
    b = [i]
    for i in range(fin):
            if a[i] < 0:
                    b = [a[i]] + b  # prepend a to b
            else:
                    b += [a[i]]     # append a to b

    print "La llista és",b

a=[1,-2,3,-4,-3,5,6]
negatius(a)

prints

La llista és [-3, -4, -2, 0, 1, 3, 5]

note that you are adding 0 to the list, i doubt that this is ok.