Thank you @dg-pb .
I have taken your suggested code snippet, made some small changes, and have played around with it in VSC’s Python debugger. The largest number in the list is 5 and as-is, the function successfully ‘bubbles it up’ (moves it) to the end. But the other elements remain in their otherwise original order.
With the equality operator, the function outputs a list where all elements are 5
. When I change that line and use the assignment operator, I get better but not the complete desired end result. I also removed the else
condition and continue
.
When I run the code with my debugger and step through, line by line, I can observe the iteration
and i
double loop variables start out at 0
and increase, one at time, as each loop progresses. So as far as I can tell, that mechanism is executing as expected.
I am not sure what else to look out for. I mean, I gather that the issue is probably with the way the two el
variables and list pointers are positioned and toss around the different list items, but I am not sure what to try next.
Here is the script I am working with now and its corresponding output:
arr = [5,3,4,1,2]
print(f"Original list: {arr}")
def bubble(arr):
for iteration in range(0,len(arr)):
for i in range(iteration):
el1 = arr[i]
el2 = arr[i+1]
if el1 > el2:
arr[i] = el2
arr[i+1] = el1
# else:
# continue
return arr
sorted_list = bubble(arr)
print(f"Final sorted list: {sorted_list}")
$ python Bubble-Sort/script3.py
Original list: [5, 3, 4, 1, 2]
Final sorted list: [3, 1, 4, 2, 5]
Executing the code, line by line makes sense. I have explored the code using my debugger rather than flattening the code outside the function. I am not even sure how that would work. I prefer to stick with the Python debugger.