Strawberry
Strawberry

Reputation: 1

how to continue bubble sorting

def bubble(v):
l = len(v)
for i in range(l-1):
    for j in range(l-i-1):
        if v[j]>v[j+1]:
            v[j+1],v[j] = v[j],v[j+1]
    return v

If I try bubble([5,4,3,2,1]) it prints 43215 I want the code to continue comparing where should I fix?

Upvotes: 0

Views: 44

Answers (2)

Raphael PICCOLO
Raphael PICCOLO

Reputation: 2175

return should be tabbed left. If you put it here it stops execution after the first iteration (of the first for-loop).

def bubble(v):
    l = len(v)
    for i in range(l-1):
        for j in range(l-i-1):
            if v[j]>v[j+1]:
                v[j+1],v[j] = v[j],v[j+1]
    return v

Upvotes: 0

SteP
SteP

Reputation: 164

I think that you just need to fix the indentation of your return. Trying putting it at the same level of the first for loop; otherwise, you will return the result (and therefore exit from your function) at the first iteration of your external loop.

Upvotes: 2

Related Questions