The following code is where I face errors:
array = [16,1,2,3,4,5] n = len(array) swapped = True while swapped == True: swapped = False for inner_index in range(1,n): first_number = array[inner_index - 1] second_number = array[inner_index] if first_number > second_number: first_number, second_number = second_number, first_number swapped = True print(array) This above code results in an infinite loop. Checking with python tutor, I noticed that it swaps the element but doesn't really "update" it in my array.
However, when I do the following, my code seems to be running:
Optimized Bubble sort algorithm code
array = [16,1,2,3,4,5] n = len(array) swapped = True #Dont forget boolean values start with a capital letter while swapped == True: swapped = False for inner_index in range(1,n): if array[inner_index - 1] > array[inner_index]: array[inner_index - 1], array[inner_index] = array[inner_index], array[inner_index-1] swapped = True print(array) What's the difference between the two?