Simple bubble sort in Python

·

0 min read

One of the first sorting algorithms that all programmers encounter is the bubble sort algorithm and for good reason, it is quite simple to implement and can be continuously relied on to sort numbers, letters or any other data that needs to be sorted from highest to lowest or vice versa. This blog post will demonstrate a bubble sort implementation using python3.

Bubble sort works by comparing two elements in a list or array and then switching them in order to position the lowest digit first or the highest digit first depending on whether one wants to sort from lowest to highest or from highest to lowest, the digits "bubble" towards their intended position until the whole set of digits is correctly sorted.

For instance, if you have an array with the numbers [3, 5, 56, 2] and wanted to sort from highest to lowest, the sorting algorithm will compare the first two digits and switch 5 with 3 because it is the bigger number, the array will then be [5, 3, 56, 2]. The algorithm will then compare the next pair of numbers in the array which are 3 and 56 and switch them so that the higher number is on the left, the algorithm will then compare the next pair until it goes the whole length of the array after which it will have completed the first pass.

After the first pass the numbers in the array will be [5, 56, 3, 2], its not quite sorted, however the numbers have 'bubbled' towards their correct order. The bubble sort algorithm will then proceed to several subsequent passes until the array is properly sorted from high to low.

The bubble sort implemented in python is as below, you can check it out by clicking this Github Gist

bubble sort.png

In the code, the outer for loop ensures that the algorithm iterates over several passes until the list is sorted while the nested for loop compares and switches the digits for each pass. Python's inbuilt random library is used to generate ten random numbers and save them in a list which the code then sorts from highest to lowest. The final statements print the unsorted and sorted list in terminal.