471,594 Members | 1,339 Online

# 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:
-------------------------------------
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 5401
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
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