[Tutor] bubble sort function
Dave Angel
davea at davea.name
Sat Nov 15 19:02:08 CET 2014
Spyros Charonis <s.charonis at gmail.com> Wrote in message:
>
> Dear group,
> I'm having a bit of trouble with understanding why my bubble sort implementation doesn't work. I've got the following function to perform a bubble sort operation on a list of numbers:
> def bubble_sort_ascending(unsorted):
> """ Sorts a list of numbers into ascending order """
> iterations = 0
> size = len(unsorted) - int(1)
> for i in range(0, size):
> unsorted[i] = float(unsorted[i])
Why are you converting some of your values to float? You should
either convert them all before you start, or not bother at
all.
> while unsorted[i] > unsorted[i+1]:
How do you think this while statement will ever run more than
once? Think about what do yoy hope this loop will do and change
it so that it will accomplish that. Hint, you'll need a second
index variable.
> # Use a tuple assignment in order to swap the value of two variables
> unsorted[i], unsorted[i+1] = unsorted[i+1], unsorted[i]
> iterations += 1
> sorted_vec = unsorted[:] # copy unsorted which is now sorted
I can't see how this accomplishes anything. Certainly if you do
want to copy the whole list, you should either do it before you
start, or when you finish.
> print "\nIterations completed: %s\n" %(iterations)
> return sorted_vec
Standard python practice is to either modify the original list,
or to return a new list, modified from the original. You're
trying to do both.
> Example: mylist = [4, 1, 7, 19, 13, 22, 17, 14, 23, 21]
>
> When I call it as such bubble_sort_ascending(mylist), it returns the list only partially sorted with 5 iterations reported, i.e.
> [1, 4.0, 7.0, 13, 19.0, 17, 14, 22.0, 21, 23.0]
> and I have to call it again
You're likely it needed only two passes. It could have taken about 9.
> for the the sorting operation to complete. Is there something I am missing in my code? Why does it not sort the entire list
A sort of this type needs at least two nested loops. You only have one.
> at once and just count all completed iterations?
You are not counting iterations, just exchanges.
--
DaveA
More information about the Tutor
mailing list