# [Tutor] bubble sort function

Alan Gauld alan.gauld at btinternet.com
Sat Nov 15 20:02:31 CET 2014

```On 15/11/14 16:46, Spyros Charonis wrote:

> def bubble_sort_ascending(unsorted):
>         iterations = 0
>         size = len(unsorted) - int(1)

Don't convert 1 to an int - it already is.

>         for i in range(0, size):

This will result in 'i' going from zero to len()-2.
Is that what you want?

>              unsorted[i] = float(unsorted[i])

Comparing ints to floats or even comparing two floats
is notoriously error prone due to the imprecision of
floating point representation. You probably don't want
to do the conversion.

And if you must do it, why do you only do it once,
outside the while loop?

>              while unsorted[i] > unsorted[i+1]:
>                    unsorted[i], unsorted[i+1] = unsorted[i+1], unsorted[i]
>                    iterations += 1

I assume you intended to end the loop body here?
But the following lines are indented so are included
in the loop.

Also because you never change 'i' the loop can only
ever run once. So really you could use a an if
statement instead of the while loop?

Finally, iterations is really counting swaps. Is that what you want it
to count or os it actually loop iterations? If so which? The for loop or
the while loop or the sum of both?

>                    sorted_vec = unsorted[:]
>                    print "\nIterations completed: %s\n" %(iterations)
>         return sorted_vec

Since you never alter sorted_vec there is no point in creating it.
Just return unsorted - which is now sorted...

> and I have to call it again for the the sorting operation to complete.
> Is there something I am missing in my code? Why does it not sort the
> entire list at once and just count all completed iterations?

There are several things missing or broken, the few I've pointed
out above will help but the algorithm seems suspect to me. You need
to revisit the core algorithm I suspect.

BTW I assume this is just a learning exercise since the default
sorting algorithm will virtually always be better than bubble
sort for any real work!

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos

```