Implementing Bubble Sort in Python3

Bubble Sort is an algorithm which is used to sort a list of elements, for example elements in an array.
The algorithm compares two adjacent elements and then swaps them if they are not in order.
The process is repeated until no more swapping is needed.

For example:
Let's take the following array: [3, 1, 5, 2]
Step 1: [1, 3, 5, 2] - the first two elements are compared and swapped.
Step 2: [1, 3, 5, 2] - the next pair is compared and not swapped, as they are in order.
Step 3: [1, 3, 2, 5] - the last two elements are swapped.

This was the first iteration over the array. Now we need to start the second iteration:
Step 1: [1, 3, 2, 5]
Step 2: [1, 2, 3, 5]
Step 3: [1, 2, 3, 5]

The third iteration will not swap any elements, meaning that the list is sorted!

The main advantage of Bubble Sort is the simplicity of the algorithm.

Bubble Sort in Python3:
def bubble_sort(nlist):

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

            for j in range(passnum):

                        if nlist[j]>nlist[j+1]:

                                        nlist[j], nlist[j+1] = nlist[j+1], nlist[j]

nlist = [14,46,43,27,57,41,45,21,70]

bubble_sort(nlist)

print(nlist)

0 Comments