I am learning algorithmic design and currently working on the most basic sorting algorithm - - Bubble Sort.
Here are two code snippets. My Python interpreter didn’t like either of them.
arr = [5,3,4,1,2]
print(f"Original list: {arr}")
def bubble(arr):
for idx1,idx2 in arr:
if idx1 > idx2:
temp = arr[idx1]
arr[idx1] == arr[idx2]
arr[idx2] = temp
else:
continue
return arr
sorted_list = bubble(arr)
print(f"Final sorted list: {sorted_list}")
Traceback:
$ python script1.py
Original list: [5, 3, 4, 1, 2]
Traceback (most recent call last):
File "/home/gnull/dev/projects/python/2018-and-2020/algos/Bubble-Sort/script1.py", line 15, in <module>
sorted_list = bubble(arr)
^^^^^^^^^^^
File "/home/gnull/dev/projects/python/2018-and-2020/algos/Bubble-Sort/script1.py", line 6, in bubble
for idx1,idx2 in arr:
^^^^^^^^^
TypeError: cannot unpack non-iterable int object
Here is a second attempt with the corresponding traceback:
arr = [5,3,4,1,2]
print(f"Original list: {arr}")
def bubble(arr):
for iteration in range(0,len(arr)):
for idx1,idx2 in arr[iteration]::
if idx1 > idx2:
temp = arr[idx1]
arr[idx1] == arr[idx2]
arr[idx2] = temp
else:
continue
return arr
sorted_list = bubble(arr)
print(f"Final sorted list: {sorted_list}")
$ python script2.py
Original list: [5, 3, 4, 1, 2]
Traceback (most recent call last):
File "/home/gnull/dev/projects/python/2018-and-2020/algos/Bubble-Sort/script2.py", line 16, in <module>
sorted_list = bubble(arr)
^^^^^^^^^^^
File "/home/gnull/dev/projects/python/2018-and-2020/algos/Bubble-Sort/script2.py", line 7, in bubble
for idx1,idx2 in arr:
^^^^^^^^^
TypeError: cannot unpack non-iterable int object
I realize I need two for loops. In my first code snippet above there is just one. So that will not do. In my second code snippet I have two for loops, but I am not referring to the two index variable (pointers) properly.
Hints and tips welcome but please avoid solving the entire algorithm for me because that would ruin my educational experience. While I am not taking for-credit courseware at a college or univeristy, I am pretending that I am. So please don’t provide a full solution.
With AI tools at my disposal, I feel like I have a strong grasp over the concept of how a Bubble Sort works in general. I asked both ChatGPT and meta.ai: “Explain a Bubble Sort algorithm using English and no computer code” which turned up some very helpful instructions to work with. My problem is modeling the English functionality in Python syntax.
What comments and suggestions might you people recommend to overcome my tracebacks above and improve my code?