Introduction
Introduction to Bubble Sort
Bubble Sort is a simple sorting algorithm that repeatedly steps through an array, compares adjacent elements, and swaps them if they are in the wrong order. With each pass, the largest unsorted element “bubbles” to its correct position at the end of the array.
This process continues, shrinking the unsorted portion of the array each time, until the entire array is sorted.
Once a full pass has been completed without sorting any elements, the process is complete and the algorithm terminates.
Visualization
Bubble Sort Visualization
Python Code
Bubble Sort Python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Track whether any swaps were made during this pass
swapped = False
for j in range(0, n - i - 1):
# Swap if the element is greater than the next
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# If no swaps were made, the array is sorted
if not swapped:
break
return arr
# Example usage
data = [64, 34, 25, 12, 22, 11, 90]
sorted_data = bubble_sort(data)
print("Sorted array:", sorted_data)
Pros and Cons of Bubble Sort
Pros and Cons of Bubble Sort
Pros
- Simple and easy to understand
- Because it’s an in-place sorting algorithm it requires minimal additional memory space
- Works well for small lists or nearly sorted lists
Cons
- Not efficient for large lists
- Time complexity is O(n^2), which means the execution time increases rapidly with the growing size of the array
- Not suitable for real-world applications with large datasets
Exam Tip
Exam Tip: Bubble Sort’s Final Pass
⚠️ Don’t forget: Bubble Sort always makes one extra pass through the array!
- Even if no swaps are needed, the algorithm still completes a final comparison pass to confirm the array is sorted.
- This final “empty” pass ensures correctness, especially when optimized with a swapped flag.
✅ When answering exam questions
- Mention or account for this last pass in your explanation or trace.
- It’s a common place where students lose marks by stopping too early.