[Tutor] bubble sort function

Spyros Charonis s.charonis at gmail.com
Sat Nov 15 17:46:26 CET 2014

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])

            while unsorted[i] > unsorted[i+1]:

                  # 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

                  print "\nIterations completed: %s\n" %(iterations)

       return sorted_vec

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 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?

Any help appreciated.

Many thanks,

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141115/24b63ba9/attachment.html>

More information about the Tutor mailing list