DSA — Bubble Sort
What is Bubble Sort?
Repeatedly steps through the list, compares adjacent elements, and swaps them if wrong order.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
Optimized Version
def bubble_sort_optimized(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break
return arr
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(n) |
| Average | O(n²) |
| Worst | O(n²) |
Characteristics
- Stable sort
- In-place
- Simple to implement
- Inefficient for large datasets
Mini Practice
- Implement bubble sort
- Add optimization
- Count comparisons and swaps
- Sort in descending order
Up Next
Continue with Selection Sort — selection sorting algorithm.
Related Topics
Frequently Asked Questions about Bubble Sort
What is Bubble Sort in DSA?
Bubble Sort is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Bubble Sort?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Bubble Sort.
Why is Bubble Sort important in DSA?
Bubble Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.