0

Just learning Python and got on to the subject of sorting lists. Two types of algorithms were shown: insertion and selection. So, I had an idea and created this:

def DiffSort(lst):
    lstDiff = [None] * len(lst)
    i = 0

    while i < len(lst):
        lstDiff[i] = lst[i] - lst[i-1] if i != 0 else lst[0]

        if lstDiff[i] < 0:
            sbj, tmp = lst[i], lstDiff[i]

            while tmp < 0:
                i -= 1
                tmp += lstDiff[i]
                lst[i+1] = lst[i]

            lst[i] = sbj
        else:
            i += 1

lst = [13,25,18,122,32,1,0.78,25,85,1,32,56,0.55,0.6,17]
print(lst)

DiffSort(lst)

print(lst)

Any good? Is there a similar method out there already?

5
  • list has a sort() method. Commented Feb 24, 2013 at 22:37
  • clever, but i think this is just insertion sort, with the downside that it won't work on arbitrary comparables (e.g. strings, tuples, etc). so it won't outdo timsort, sorry :) Commented Feb 24, 2013 at 22:43
  • Are you looking for the best way to normally sort a list in Python, or are you interested in the theory of sorting algorithms? Commented Feb 24, 2013 at 22:44
  • 1
    He's obviously interested on sorting algorithms... and everyone keep answering as if he just asked how to sort a list xD Anyway, OnT: the lstDiff list seems superfluous, you are only using the current index (which could be replaced by a simple variable). Also, agree with Eevee and that it seems like insertion sort using diff instead of conditionals. Commented Feb 24, 2013 at 22:52
  • Cheers for the feedback, working my way through an introduction to Python. Just seeing if I was on to something there... lol. Commented Feb 24, 2013 at 23:15

2 Answers 2

1

list.sort() if you want to sort a list in-place.

sorted(list) if you want to return a sorted copy of the list.

The second option works with any iterable type, whereas the first is list-exclusive (although some other types may have the same or a similar function defined as well, but you can generally not expect that).

Since you seem to care about the algorithmic part of it, this may be of interest to you: http://svn.python.org/projects/python/trunk/Objects/listsort.txt

Sign up to request clarification or add additional context in comments.

1 Comment

Cheers, looks interesting.
0

Isn't lst.sort() good enough? It's bound to be much faster than a Python solution that has to run in O(n^2) time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.