Connecting Tech Pros Worldwide Help | Site Map

How to make a sort function?

Newbie
 
Join Date: Mar 2009
Posts: 4
#1: Mar 19 '09
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:
-------------------------------------
Expand|Select|Wrap|Line Numbers
  1. def sort(l):
  2.     """sort a list of #s"""
  3.     for i in range(len(l)-1):
  4.         if l[i] > l[i+1]:
  5.             l[i+1], l[i] = l[i], l[i+1]
  6.     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?
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,561
#2: Mar 19 '09

re: How to make a sort function?


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.
Expand|Select|Wrap|Line Numbers
  1.     for j in range(len(L)-1, 0, -1):
  2.         for idx in range(j):
  3.  
Newbie
 
Join Date: Mar 2009
Posts: 4
#3: Mar 19 '09

re: How to make a sort function?


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

Expand|Select|Wrap|Line Numbers
  1.     for j in range(0, len(l3)-1):
  2.         for i in range(j):
  3.  
a bit different from urs but works the same.

again, really appreciate the help. :D
Reply