Similar Posts

Subscribe
Notify of
3 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
MrAmazing2
10 months ago

First, you have ifs [0] and [1] instead of [i] and [i+1] used, that is already wrong.

Second, you need Member State and not ). Otherwise, i+1 is an invalid index.

Thirdly, this only brings the greatest number to the right end.
Imagine the 6 would be left. Now go through the code piece by piece:
You are comparing the first number with the second one and if the first one is larger. The 6 is now second. Now you compare the second place with the third and exchange it. 6 is only in the third place. etc. You just take the largest number to the right.

To sort the complete list with this procedure, you need another loop to repeat the whole thing:

Feld = [5,4,3,4,5,6]

for _ in range(6):
    for i in range(5):
      if Feld[i]>Feld[i+1]:
        h = Feld[i]
        Feld[i] = Feld[i+1]
        Feld[i+1] = h

print(Feld)
MrAmazing2
10 months ago
Reply to  MrAmazing2

You could still optimize the code by not always letting the inner loop run completely to the end, because the numbers on the right are already sorted. But I’ll save you, the code is running anyway? 😀

Erzesel
10 months ago
Reply to  MrAmazing2

In Python you do not need an auxiliary variable for a swap

Field[i+1],Field[i] = Field[i],Field[i+1]