469,271 Members | 1,547 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,271 developers. It's quick & easy.

How to make a sort function?

4
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?
Mar 19 '09 #1
2 5208
bvdet
2,851 Expert Mod 2GB
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.  
Mar 19 '09 #2
calred
4
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
Mar 19 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by its me | last post: by
5 posts views Thread by Dr. Ann Huxtable | last post: by
7 posts views Thread by Stuart | last post: by
20 posts views Thread by Xah Lee | last post: by
6 posts views Thread by scottyman | last post: by
28 posts views Thread by Steven Bethard | last post: by
7 posts views Thread by Steven Bethard | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.