Search code examples
pythonalgorithmpython-3.xbubble-sort

Python 3: Optimised Bubble Sort


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.


Solution

  • Here's some skeleton code that shows how to scan the array forwards and backwards, while shrinking the list on each iteration.

    values = 100,101,102,103,104,105
    
    start = 0
    stop = len(values)-1
    
    while stop > start:
        for i in range(start, stop):
            print i, "compare", values[i], "with", values[i+1]
        print "moved a large value to index", stop
        print
    
        stop = stop - 1
        if stop == start:
            break
    
        for i in range(stop, start, -1):
            print i, "compare", values[i], "with", values[i-1]
        print "moved a small value to index", start
        print
    
        start = start + 1