home menu IT - Hardware IT - Software Inventions Tech Guides About

Bubble Sorting Algorithm - 02/03/19

There are many sorting algorithms for arranging an unordered array of numbers in ascending or descending order. Some sorting algorithms are more efficient when the array to be sorted is radically disorganised (e.g: [6,20,7,1,900,3,4,1,78,2,53,100]). However, other sorting algorithms are more efficient when handling only slightly disorganised arrays of numbers (e.g. [1,2,4,3,5,7,6,5,8,9,10]). Below is my Python implementation of a bubble sort algorithm. This algorithm falls into the latter catogory (more efficient when dealing with only slightly disorganised arrays). A bubble sort works by looking through the disorgsanised array and swapping adjacent pairs of numbers if the latter number is lower than the former number (e.g: [5,3] would be converted to [3,5] assuming that ascending order is desirable). Over many "sweeps" of the algorithm through the array, the highest numbers in the array "bubble" their way to the top of the array and the lowest numbers sink to the bottom.

Run the following Trinket Python interpreter in which my Python programme can be tested with any array as inputted by the user:

This approach to sorting an array is generally considered very inefficient: the number of operations required to fully sort an array increases with the square of the number of elements in the original (unsorted) array. Furthermore, on any given "sweep" of the array, it is not guaranteed that every stage of the "sweep" will actually make any changes; it may just happen to verify that a section of the array is already ordered. If an element is radically out of place, it will take many "sweeps" to actually bring it to its correct location in the array; this is why bubble sort is a particularly poor choice for ordering very incorrectly-ordered arrays.