← Back to cc

Bubble Sort in Python

Learn about Bubble Sort, the simplest way to sort an array

BeginnerSortingArraysPython

Sorting Algorithms

For all examples, assume a dummy array, like x = [-5,-3,2,1,-3,-3,7,2,2] This could be any array, but this is simply an example to work with. We are sorting this array in ASCENDING order.

Bubble Sort

Think of this as a bubbling effect that goes through the entire dataset and makes elements bubble into their appropriate positions.

Example:

Algorithm:

Complexity:

Python code for bubble sort:

x = [-5,-3,2,1,-3,-3,7,2,2] # dummy array 

flag = True # variable to see if we should keep looping

while flag: # keep looping through array, to fully sort
    flag = False # set false after no more switches are made, exit loop
    for i in range(1, len(x)): # for indexs 1 through length - 1 (we don't want 0 because we are subtracting by one)
        if(x[i] < x[i-1]): # if the last index is bigger than the current index
            x[i], x[i-1] = x[i-1], x[i] # swap the values
            flag = True # a swap occurred, so continue the loop
            
print(x)