please help. I need to optimize my Bubble Sort algorithm in order to get less total comparisons than the non-optimised bubbleSort. I managed to create just the 'Normal Bubble sort (only travels from left to right):
def bubbleSort(values):
n = len(values) - 1
swap = True
ncomp = 0 # My total comparisons counter
while swap:
swap = False
for i in range(n): # i = 0, 1, 2, ..., n-1
ncomp += 1
if values[i] > values[i+1]:
temp = values[i]
values[i] = values[i+1]
values[i+1] = temp
swap = True
return values, ncomp
So basically i dont know how to create an 'optimised bubbleSort', a bubbleSortPlus function in which bubbles travel in both directions: from left to right, immediately followed by a travel from right to left. In theory, in each pass the travel of the bubbles should be shortened (saving in a variable the position of the last swap in a travel, and make the next travel start at that position. I tried so hard but i'm just a python newbie, please help.