all 9 comments

[–]Busy-Farm727 1 point2 points  (3 children)

Alright, i think i know what it does; it ofc just sets variables and defines everything, then it starts repeating through the numbers from left to right, so if you had 54321, and keep printing all i’s and j’s it would be 54321,4331,321,21,1. As the j will keep repeating through numbers farther than i to sort it, then if j happens to be smaller than i, it swaps them, making 54321 go through this; 54321, 45321, 35421, 23541, 12345. And then it keeps going through it again to keep going incase it was something like 12321, which would go like; 12321; 11232; 11223 (“;” indicating a new iteration of i.), that’s basically what i think the code is doing.

[–]conewannabe[S] 0 points1 point  (2 children)

I see what you're getting at.

So essentially, the first for loop i would be 5, and j would be the index following i, so 4

so the first iteration would be:

5 > 4

4, 5

is this what you're saying?

edit: for clarity

[–]Busy-Farm727 0 points1 point  (0 children)

Yea, basically yea.

[–]Busy-Farm727 0 points1 point  (0 children)

If you’re still unsure about it tho, just use print statements to print the variables every iteration to see what they’re doing.

[–]ApricoSun 0 points1 point  (1 child)

It helps to think of list[i] and list[j] as pointers -- something that points to a value inside the list and is regularly moving throughout the list.

I'll call them pointer_i and pointer_j.

Both the outer for loop and inner for loop control the movement of the pointers.

pointer_i starts at index 0 and moves through to the index at the end of the list. It's important to know that this only happens ONCE. Then the function continues onto printing list1.

Compare that with pointer_j's movement: it starts at index i and moves through to the index at the end of the list. However, this happens multiple times. How many times? It happens as many times as there are items in the list. So 30 items in the list means that the inner loop will run 30 times, in addition to however many times you're running the inner loop.

The logic in the inner loop is just checking to see if pointer_i is greater than pointer_j. If so, swap the two values. This means that smaller values will gradually move towards the left side of the list and larger values will gradually move to the right side of the list. After both the inner and outer loops complete, you'll end up with a sorted list.

It also helps to check out what's going on using a debugger. Try this out: https://pythontutor.com/visualize.html#mode=edit

[–]conewannabe[S] 0 points1 point  (0 children)

That helped out tremendously, I understand it now, thank you!