Bubble Sort in Python
Palavras-chave:
Publicado em: 03/08/2025Bubble Sort in Python
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. This article aims to provide a clear and comprehensive understanding of Bubble Sort, its implementation in Python, and its performance characteristics.
Fundamental Concepts / Prerequisites
Before diving into the implementation, it's important to have a basic understanding of the following:
- Python syntax and data types (lists, integers).
- Basic programming concepts (loops, conditional statements).
- The concept of sorting algorithms.
Core Implementation
def bubble_sort(data):
"""
Sorts a list of numbers using the Bubble Sort algorithm.
Args:
data: A list of numbers to be sorted.
Returns:
A new list containing the sorted numbers.
"""
n = len(data)
data_copy = data[:] # Create a copy to avoid modifying the original list
for i in range(n):
# Flag to optimize: if no swaps occur in a pass, the list is sorted
swapped = False
for j in range(0, n - i - 1):
# Compare adjacent elements
if data_copy[j] > data_copy[j + 1]:
# Swap if they are in the wrong order
data_copy[j], data_copy[j + 1] = data_copy[j + 1], data_copy[j]
swapped = True
# If no two elements were swapped in inner loop, the array is sorted
if not swapped:
break
return data_copy
# Example usage
numbers = [5, 1, 4, 2, 8]
sorted_numbers = bubble_sort(numbers)
print(f"Original list: {numbers}")
print(f"Sorted list: {sorted_numbers}")
Code Explanation
The bubble_sort(data)
function takes a list of numbers as input.
First, we get the length of the input list (n = len(data)
) and create a copy of the list data_copy
to avoid modifying the original list in place. This is a good practice in function design unless modifying the original data is explicitly intended.
The outer loop (for i in range(n)
) iterates through the list `n` times. Each pass "bubbles" the largest unsorted element to its correct position at the end of the list.
The inner loop (for j in range(0, n - i - 1)
) compares adjacent elements (data_copy[j]
and data_copy[j + 1]
). If they are in the wrong order, they are swapped.
The swapped
flag is used for optimization. If no swaps occur during a pass of the inner loop, it means the list is already sorted, and the outer loop can be terminated early using the break
statement.
Finally, the function returns the sorted list.
Complexity Analysis
The time complexity of Bubble Sort is O(n2) in the average and worst-case scenarios. This is because, in the worst case (e.g., a list sorted in reverse order), the algorithm needs to compare and potentially swap each pair of adjacent elements in each pass. In the best-case scenario (e.g., a list that is already sorted), the time complexity is O(n) due to the optimization with the `swapped` flag.
The space complexity of Bubble Sort is O(1) because it sorts the list in place, requiring only a constant amount of extra memory for temporary variables (like the `swapped` flag and the temporary variable used for swapping).
Alternative Approaches
One alternative sorting algorithm is Insertion Sort. Insertion Sort also has a time complexity of O(n2) in the average and worst cases, but it generally performs better than Bubble Sort in practice. Merge Sort, Quicksort, and Heapsort all offer O(n log n) average-case time complexity, but typically require O(n) space (Merge Sort) or more complex implementation (Quicksort, Heapsort).
Conclusion
Bubble Sort is a simple and easy-to-understand sorting algorithm. However, due to its quadratic time complexity, it is not suitable for large datasets. For larger datasets, more efficient sorting algorithms like Merge Sort or Quicksort are generally preferred. The primary value of Bubble Sort lies in its educational simplicity and ability to illustrate fundamental sorting principles.