How to make a sort function?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • calred
    New Member
    • Mar 2009
    • 4

    How to make a sort function?

    i want to create a function that does the same as the build-in function .sort(), but it is more difficult than i think.

    my function is as below:
    -------------------------------------
    Code:
    def sort(l):
        """sort a list of #s"""
        for i in range(len(l)-1):
            if l[i] > l[i+1]:
                l[i+1], l[i] = l[i], l[i+1]
        print l
    -------------------------------------

    i tried sort([32,25,31,3,6,4, 0]), but the output only had sorted the some of the numbers. it gave [25, 31, 3, 6, 4, 0, 32] instead of giving me a list of ascending numbers.

    where went wrong with my function?
    Last edited by bvdet; Mar 19 '09, 02:10 PM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Please use code tags when posting code.

    What you want is a bubble sort, I think. You code only uses one for loop, but it requires two. For a list of 100 elements, 10000 comparisons are required.
    Code:
        for j in range(len(L)-1, 0, -1):
            for idx in range(j):

    Comment

    • calred
      New Member
      • Mar 2009
      • 4

      #3
      Hi, thx for advise!
      i added another loop so the func is now:

      Code:
          for j in range(0, len(l3)-1):
              for i in range(j):
      a bit different from urs but works the same.

      again, really appreciate the help. :D

      Comment

      Working...