martian94
Coder
Hello! I'm new to coding and I am in the noob phase. I am tasked with creating a bubble sort algorithm. My problem is, hopefully, quite simple to you. The iterations in the print statements seem to sort the numbers list right away, instead of printing each iteration of two numbers switching places. It should go like:
Given numbers: [5, 3, 1, 2, 4]
Iteration 1: [3, 5, 1, 2, 4] > [3, 1, 5, 2, 4] > [3, 1, 2, 5, 4] > [3, 1, 2, 4, 5]
Print 3, 1, 2, 4, 5
Iteration 2: [1, 3, 2, 4, 5] > [1, 2, 3, 4, 5] (now 3, 4 and 5 is correctly placed)
Print 1, 2, 3, 4, 5
Iteration 3: [1, 2, 3, 4, 5] (what happened here is compare 1 and 2, no need to swap)
Print 1, 2, 3, 4, 5
Final result: [1, 2, 3, 4, 5].
But it does not go this way. Instead it prints
[3, 1, 2, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Final result: [1, 2, 3, 4, 5]
[...]
Actually, no. I saw this is in fact right now. I just did the iterations on paper and I see it is right, it is just the fact that there are no switches in the last iterations which makes it look weird. It works as expected with a list [5, 4, 3, 2, 1] for example. I'll post this anyway in hopes it helps somebody else.
Given numbers: [5, 3, 1, 2, 4]
Iteration 1: [3, 5, 1, 2, 4] > [3, 1, 5, 2, 4] > [3, 1, 2, 5, 4] > [3, 1, 2, 4, 5]
Print 3, 1, 2, 4, 5
Iteration 2: [1, 3, 2, 4, 5] > [1, 2, 3, 4, 5] (now 3, 4 and 5 is correctly placed)
Print 1, 2, 3, 4, 5
Iteration 3: [1, 2, 3, 4, 5] (what happened here is compare 1 and 2, no need to swap)
Print 1, 2, 3, 4, 5
Final result: [1, 2, 3, 4, 5].
But it does not go this way. Instead it prints
[3, 1, 2, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Final result: [1, 2, 3, 4, 5]
[...]
Actually, no. I saw this is in fact right now. I just did the iterations on paper and I see it is right, it is just the fact that there are no switches in the last iterations which makes it look weird. It works as expected with a list [5, 4, 3, 2, 1] for example. I'll post this anyway in hopes it helps somebody else.