A bubble sort in Python

As a second exercise in preparation for my Microsoft phone interview, I give you the Python bubble sort (or sinking sort). Once again, this is just an exercise. You should use the standard Python facilities for your sorting needs, especially given the terrible efficiency of bubble sort.

from random import shuffle

countries = ["Afghanistan","Albania","Algeria", ...]
sorted_countries = countries


def bubblesort(items):
    dirty = True
    while dirty:
        dirty = False
        for index, item in enumerate(items[1:]):
            if items[index-1] > items[index]:
                tmp = items[index]
                items[index] = items[index-1]
                items[index-1] = tmp
                dirty = True
    return items

print bubblesort(countries)

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax