By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,171 Members | 809 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,171 IT Pros & Developers. It's quick & easy.

How to make a sort function?

P: 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
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
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

P: 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.