Bubble Sort is the simplest sorting algorithm. It works by repeatedly stepping through the list, comparing each pair of adjacent items, and swapping them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
The algorithm gets its name because smaller elements "bubble" to the top of the list with each pass. While it's easy to understand, it is too slow for most real-world scenarios.
Here is a function that implements the bubble sort algorithm. We can add a small optimization to stop the algorithm early if the list is already sorted.
def bubble_sort(data):
n = len(data)
// Traverse through all array elements
for i in range(n):
// A flag to optimize. If no swaps in a pass, list is sorted.
swapped = False
// Last i elements are already in place
for j in range(0, n-i-1):
// traverse the array from 0 to n-i-1
// Swap if the element found is greater than the next element
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j]
swapped = True
if not swapped:
break // Exit loop if list is already sorted
// --- Usage ---
my_list = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(my_list)
print("Sorted list is:", my_list)
Bubble sort has a simple but poor performance profile.
swapped flag optimization, it only takes one pass to confirm.Why learn Bubble Sort? It's a great algorithm for beginners to learn because its logic is very straightforward. It serves as a gentle introduction to the concept of sorting algorithms and complexity analysis before moving on to more efficient methods.
What is the worst-case time complexity of Bubble Sort?