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
sorted

                  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,

Spyros
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to