#πŸ”’ bubblesort problem

7 messages Β· Page 1 of 1 (latest)

rich spear
#

hey folks, I'm pretty new to programming in general and currently trying to learn python πŸ™‚

I'm prepping for my finals atm and don't know how to proceed with my bubblesort code:

`arr = []
length = int(input("wie lang soll das array sein?"))

for g in range(length):
arr.append (random.randrange(1,200,1))

print(arr)

i = 1
j = 1
while i < length - 1 :

while j < length - 1:
    
    if arr[j] > arr[j+1]:
        zwischen = arr[j+1]  
        arr[j+1] = arr[j]
        arr[j] = zwischen
        j = j+1
        if j == length -1 :
            j = 1
            
i = i+1

print(arr)

`
i know that my code runs forever but I need a hint on how to design j in a way that the program just jumps to the beginning (more efficient ways such as list length descrease will be done later)

wind umbraBOT
#

@rich spear

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

brisk hemlock
#

i know that my code runs forever but I need a hint on how to design j in a way that the program just jumps to the beginning
the easiest way is to use for instead of while, but the 2 won't be that different anyways
the problem arises here

while i < length - 1 :
    while j < length - 1:
        if arr[j] > arr[j+1]:
            zwischen = arr[j+1]  
            arr[j+1] = arr[j]
            arr[j] = zwischen
            j = j+1
            if j == length -1 :
                j = 1  # <--
```you reset `j` before it can break out of the loop, so you have an infinite
to fix that, just move the resetting to somewhere outside the `while j < length - 1:` block
#

and also, j = j+1 shouldn't be in the if check

wind umbraBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.