Bubble Sort Algorithm

Bubble-sort-1-9The Bubble sort algorithm is one of the key sorting algorithms used in Computer Science. It is a fairly simple algorithm to implement and is particularly useful when you need to find the top x values of a list.

The algorithm starts at the beginning of the data set. It compares the first two value, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent values to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass.

This algorithm’s average and worst-case performance is O(n2), so it is rarely used to sort large, un-ordered data sets. Bubble sort can be used to sort a small number of items and is a lot more effective on data sets where the values are already nearly sorted.

Python Implementation of a Bubble Sort algorithm

The Python code belows let you visualise how a Bubble sort algorithm with a small set of values (from 1 to 9). The list of values is shuffled every time you run this code.

Share Button
Tagged with: ,