I have been at it for quite some time and I have not been able to solve the error ('int' object is not subscriptable) that is happening on my 4th line of code below.
I want the my counter variable to be compared to the previous index in the array, and if the element at the immediately previous index is larger, they are swapped.
Any suggestions would be appreciated!
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))enter code here
In the line:
list_of_numbers = temp
you are assigning an integer to the variable list_of_numbers
which causes the error.
So instead, use:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
temp = list_of_numbers[j-1]
list_of_numbers[j-1] = list_of_numbers[j]
list_of_numbers[j] = temp
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))
or a better variable swap:
def bubble_sort(list_of_numbers):
for i in range(len(list_of_numbers)):
for j in range(1,len(list_of_numbers)- i):
if list_of_numbers[j-1] > list_of_numbers[j]:
list_of_numbers[j],list_of_numbers[j-1] = list_of_numbers[j-1],list_of_numbers[j]
return list_of_numbers
unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))