Python: BubbleSort algorithm


Video is ready, Click Here to View ×

Tutorial on how to write a BubbleSort program in Python 3 with animated demo and code implementation example.

22 thoughts on “Python: BubbleSort algorithm

  1. def bubblesort(mylist):

    for i in range (0, len(mylist)-1):

    for j in range ( 0, len(mylist)-1-i):


    return mylist



    not able to sort accounding to your code
    why this error i coming

    ['09', '80', '45', '2', '110', '60']

  2. _sorted = False
    while not _sorted:
    _sorted = True

    for i in range(len(a)-1):
    if a[i] > a[i+1]:
    a[i], a[i + 1] = a[i + 1], a[i]
    _sorted = _sorted and False

    _sorted = _sorted and True

    I did it think way. Isn't it necessary to jump back to the top of the loop because we can't be certain the the minimum value will be placed at index 0?

  3. Hi,

    Can you explain how the range() function takes for arguments in line 5 at 1:47? I thought it could only take 3 and they had to be separated by a comma; like this: range(start, stop, step)

    Anyway well done, and very well explained

  4. i think the code is not much reliable for long list as i am getting the less one step to output

    def bubbleSort(List):
    for i in range(0,len(List)-1):
    for j in range(0,len(List)-1-i):
    if List[j]>List[j+1]:

    return List

  5. I believe your swap is wrong. You should have a tmp variable storing myList[j] since you are assigning the value of myList[j]=myList[j+1] then you are saying myList[j+1]=myList[j] they will equal the same thing

  6. Thanks for this video! I decided to implement the bubble sort function using while statements.

    def bubbleSort ( alist ) :
    i, j = 0, 0
    while ( i < (len(alist) – 1) ) :
    while (j < (len(alist) – 1 – i) ) :
    if (alist[j] > alist[j+1]) :
    alist[j], alist[j+1] = alist[j+1], alist[j] #- swap values
    j = j + 1
    i, j = (i+1), 0 # increment i, reset j to zero!
    return alist

Leave a Reply

Your email address will not be published. Required fields are marked *