[Tutor] sorting algorithm

C.T. Matsumoto tmatsumoto at gmx.net
Wed Mar 3 10:56:23 CET 2010


Hello,

This is follow up on a question I had about algorithms. In the thread it 
was suggested I make my own sorting algorithm.

Here are my results.

#!/usr/bin/python

def sort_(list_):
    for item1 in list_:
        pos1 = list_.index(item1)
        pos2 = pos1 + 1
        try:
            item2 = list_[pos2]
        except IndexError:
            pass

        if item1 >= item2:
            try:
                list_.pop(pos2)
                list_.insert(pos1, item2)
                return True
            except IndexError:
                pass

def mysorter(list_):
    while sort_(list_) is True:
        sort_(list_)

I found this to be a great exercise. In doing the exercise, I got pretty 
stuck. I consulted another programmer (my dad) who described how to go 
about sorting. As it turned out the description he described was the 
Bubble sort algorithm. Since coding the solution I know the Bubble sort 
is inefficient because of repeated iterations over the entire list. This 
shed light on the quick sort algorithm which I'd like to have a go at.

Something I haven't tried is sticking in really large lists. I was told 
that with really large list you break down the input list into smaller 
lists. Sort each list, then go back and use the same swapping procedure 
for each of the different lists. My question is, at what point to you 
start breaking things up? Is that based on list elements or is it based 
on memory(?) resources python is using?

One thing I'm not pleased about is the while loop and I'd like to 
replace it with a for loop.

Thanks,

T


More information about the Tutor mailing list