sort functions in python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 8 21:34:20 EST 2008


On Fri, 08 Feb 2008 17:00:27 -0800, t3chn0n3rd wrote:

> Do you think it is relatively easy to write sort algorithms such as the
> common Bubble sort in Python as compared to other high level programming
> langauges


You realise that bubble sort is one of the worst possible sort algorithms 
possible, particularly on modern hardware? It's not the worst: bogo sort 
and bozo sort are worse, but bubble sort is still pretty atrocious.

http://en.wikipedia.org/wiki/Bogosort

Frankly, you won't get better performance in Python than the built in 
list.sort() method and sorted() function provide. If you want to actually 
sort, use them.

But for the sake of the learning exercise, yes, Python makes it easy to 
write algorithms including bubble sort and quick sort and merge sort.

Here's a version of bubble sort, from Wikibooks:

def bubblesort(l):
     "Sorts l in place and returns it."
     for passesLeft in range(len(l)-1, 0, -1):
         for index in range(passesLeft):
             if l[index] > l[index + 1]:
                l[index], l[index + 1] = l[index + 1], l[index]
     return l

http://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Bubble_sort



-- 
Steven



More information about the Python-list mailing list