AI Mentor
24/7 coding assistant powered by AI
AI Coding Mentor
How do I optimize this bubble sort algorithm?
Great question! Bubble sort has O(n²) time complexity. Here are several optimization strategies: 1. **Early termination**: Add a flag to detect if no swaps occurred 2. **Reduce comparisons**: After each pass, the largest element is in place 3. **Consider alternatives**: Quick sort or merge sort for better performance Would you like me to show you the optimized code?
def optimized_bubble_sort(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 arrThat's helpful! Can you explain the time complexity improvement?
Absolutely! The optimization improves performance in these ways: **Best Case**: O(n) - when array is already sorted, we exit early **Average Case**: Still O(n²) but with fewer operations **Worst Case**: O(n²) - no change for reverse sorted array The early termination flag saves unnecessary passes when the array becomes sorted before completing all iterations.