Skip to main content

Bubble Sort Demystified: A Beginner-Friendly Tutorial with Python 3 Examples

Bubble Sort is one of the simplest sorting algorithms to understand and implement. It's perfect for beginners who want to get their hands dirty with algorithmic concepts right away. In this tutorial, we'll go through what Bubble Sort does, how it works, and provide a clear example in Python 3.

What is Bubble Sort?

Bubble Sort is an elementary sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until the list is sorted. The name "Bubble Sort" comes from the way smaller elements "bubble" to the top of the list (beginning) with each iteration.

Python Implementation

Here's a well-commented implementation of Bubble Sort in Python:

def bubble_sort(arr):
    n = len(arr)
    
    # Traverse through all array elements
    for i in range(n):
        # Last i elements are already sorted, no need to check them
        for j in range(0, n-i-1):
            # Swap if the element found is greater than the next element
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
                
    return arr

# Example usage:
example_list = [64, 34, 25, 12, 22, 11, 90]
sorted_list = bubble_sort(example_list)
print("Sorted array is:", sorted_list)

Explanation of the Code

  • Function Definition: We define a function bubble_sort that takes a list arr as its parameter.
  • Outer Loop: The outer loop runs over each element in the list. It ensures we go through the entire list multiple times if necessary.
  • Inner Loop: This loop goes up to the unsorted portion of the list, comparing adjacent elements.
  • Swapping Elements: If an element is greater than the next one (arr[j] > arr[j+1]), they are swapped. This pushes larger elements towards the end of the list with each pass.

Example Demonstration

Let's see how our Bubble Sort implementation works with a small example:

example_list = [64, 34, 25, 12, 22, 11, 90]
sorted_list = bubble_sort(example_list)
print("Sorted array is:", sorted_list)

Input: [64, 34, 25, 12, 22, 11, 90]
Output: Sorted array is: [11, 12, 22, 25, 34, 64, 90]

Time Complexity

Bubble Sort has a time complexity of O(n²) in the worst and average cases. This makes it inefficient on large lists compared to more advanced algorithms like QuickSort or MergeSort. However, its simplicity is what makes it educational.

Conclusion

While Bubble Sort might not be the most efficient sorting algorithm for practical use with large datasets, it's an excellent starting point for understanding how sorting works. By implementing and experimenting with Bubble Sort, you'll gain a solid foundation in basic algorithmic thinking which will help as you tackle more complex problems.

Happy coding!


Comments