Search code examples
pythonalgorithmbubble-sort

Bubble sort algorithm - do i have an error?


I was following an online website tutorial on bubble sort and decided to do it myself before looking at the answer.

I get this:

 def bubbleSort(theList):
     i=0
     while i < len(theList)-1:
         if theList[i+1] < theList[i]:
             theList[i],theList[i+1] = theList[i+1],theList[i]
         i=i+1

     return theList

 myList = [13,5,6,2,10,11]
 print(bubbleSort(myList))

but in the answer they have:

 def bubbleSort(alist):
     for passnum in range(len(alist)-1,0,-1):
         for i in range(passnum):
             if alist[i]>alist[i+1]:
                 temp = alist[i]
                 alist[i] = alist[i+1]
                 alist[i+1] = temp

 alist = [54,26,93,17,77,31,44,55,20]
 bubbleSort(alist)
 print(alist)

the problem i have is that my answer works but i dont understand why there is an extra line in the example answer:

  for passnum in range(len(alist)-1,0,-1):

whats the point of this? also in other examples i also see 2 for loops being used. is there an error with my code? it seems to work


Solution

  • You make just one pass of the bubble sort. You code is correct, but it only brings the one, largest element to the end of the list. You should repeat the code n times, with the range reducing by one each time.

    You should note that your code has complexity O(n), which bubblesort has O(n^2).