DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 28: Python Bubble Sort, Implement a Simple Sorting Algorithm with Nested Loops

Welcome to Day 28 of the #80DaysOfChallenges journey! This beginner-to-intermediate challenge steps into implementing the Bubble Sort algorithm, where you sort a list by repeatedly swapping adjacent elements that are out of order. It highlights nested loops in action, showing how passes through the list bubble up the largest values, a foundational way to grasp sorting mechanics. If you're moving from basic loops to algorithms or curious about how sorts work under the hood, this "Python bubble sort" guide details a function that's straightforward to code and debug, with an optimization to stop early if sorted.


💡 Key Takeaways from Day 28: Bubble Sort Function

This task builds a function that sorts numbers in place using comparisons and swaps, returning the ordered list. It's a classic intro to algorithms: loop over passes, check pairs, adjust as needed. We'll break it into function with length and flag, nested loops for swaps, and early exit plus tests.

1. Function Design: Length and Swap Flag

The bubble_sort function modifies the input list directly and returns it. Its signature is basic:

def bubble_sort(numbers):
    """
    Sorts a list of numbers using the Bubble Sort algorithm.
    """
Enter fullscreen mode Exit fullscreen mode

Grab the length:

n = len(numbers)
Enter fullscreen mode Exit fullscreen mode

Then loop over passes:

for i in range(n):
    swapped = False  # Track if any swap happened in this pass
Enter fullscreen mode Exit fullscreen mode

swapped acts as a sentinel to detect if the list is already ordered. This design keeps mutations in place for efficiency on small lists, and it's easy to plug into code needing sorted data without extras.

2. Nested Loops: Comparisons and Swaps

Inside, the inner loop scans unsorted parts:

for j in range(0, n - i - 1):
    if numbers[j] > numbers[j + 1]:
        # Swap the elements
        numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
        swapped = True
Enter fullscreen mode Exit fullscreen mode

The if > checks pairs, swapping if needed. The range shrinks with n - i - 1 since each pass fixes the end. It's a clear view of how sorts progress, one bubble at a time, and works for any comparable items, not just numbers.

3. Early Exit: Optimization and Example Tests

After the inner loop:

# If no swaps occurred, the list is already sorted
if not swapped:
    break
Enter fullscreen mode Exit fullscreen mode

This skips unnecessary passes. Tests confirm:

print(bubble_sort([5, 1, 4, 2, 8]))   # -> [1, 2, 4, 5, 8]
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))  # -> [11, 12, 22, 25, 34, 64, 90]
print(bubble_sort([3, 2, 1]))  # -> [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

For [5,1,4,2,8], it swaps step-by-step to sort. The flag shines on nearly sorted lists, cutting runtime. It's a tweak that makes the algo smarter without complexity.


🎯 Summary and Reflections

This Bubble Sort implementation reveals the nuts and bolts of sorting, using loops to methodically order data. It stood out to me:

  • Loop interplay: Outer for passes, inner for pairs, a pattern for many algos.
  • Optimization value: The flag turns O(n^2) worst-case into better averages.
  • In-place sorting: Modifies original, saves space for simple needs.

Realized how this builds intuition for faster sorts like quicksort. For fun, visualize with prints in the loop to see swaps happen.

Advanced Alternatives: Add descending with a param, or compare to sorted() for efficiency. How do you teach sorting? Drop thoughts below!


🚀 Next Steps and Resources

Day 28 bridged basics to algos, priming for more computational tasks. In #80DaysOfChallenges? Timed it or added visuals? Share your take!

Top comments (0)