Back to Python
2026-02-145 min read

Bubble Sort (Python Programming)

Learn Bubble Sort (Python Programming) step by step with clear examples and exercises.

Why This Matters

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This guide will walk you through implementing bubble sort in Python, its practical uses, common mistakes to avoid, and practice questions to help solidify your understanding.

Why Bubble Sort Matters

Bubble sort is a fundamental algorithm that serves as an introduction to sorting algorithms. It's essential for beginners to understand the mechanics of this algorithm because it provides a foundation for more complex algorithms like quicksort, mergesort, and heapsort. Additionally, bubble sort may be useful in situations where the input data size is small or when performance is not a critical concern.

In interviews, understanding bubble sort can help you answer questions related to sorting algorithms and their efficiency. It's also crucial to recognize its limitations, such as poor performance on large datasets, which can help you make informed decisions about choosing the appropriate sorting algorithm for specific problems.

Prerequisites

To follow this guide, you should have a basic understanding of Python programming concepts, including:

  • Variables and data types (e.g., integers, strings, lists)
  • Control structures (e.g., if statements, loops)
  • List manipulation (e.g., indexing, slicing)

Core Concept

Algorithm Steps

  1. Initialize a flag variable swapped to track whether any swaps were made in the current pass through the list. If no swaps are made, it means the list is already sorted, and we can exit the algorithm early.
  2. Iterate through the list from the first element (index 0) to the second-to-last element (index n - 2). In each iteration, compare adjacent elements and swap them if they are in the wrong order.
  3. After comparing all pairs of adjacent elements, check the value of the flag variable swapped. If it's False, the list is sorted, and we can exit the algorithm. Otherwise, repeat step 2 for another pass through the list.
  4. Continue this process until the flag variable swapped is False, indicating that the list is sorted.

Implementation in Python

def bubble_sort(arr):
n = len(arr)
swapped = True
for i in range(n - 1):
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
return arr

Worked Example

Let's sort the following list using bubble sort: [64, 34, 25, 12, 22, 11, 90].

  1. Initialize the flag variable swapped to True.
  2. Iterate through the list for the first pass (from index 0 to 5):
  • Compare 64 and 34, swap them because 64 > 34: [34, 64, 25, 12, 22, 11, 90].
  • Compare 34 and 25, no need to swap because 34 <= 25: [25, 34, 64, 12, 22, 11, 90].
  • Compare 25 and 12, swap them because 25 > 12: [12, 25, 34, 64, 22, 11, 90].
  • Compare 12 and 64, swap them because 12 < 64: [12, 25, 34, 64, 22, 11, 90].
  • Compare 25 and 34, swap them because 25 < 34: [12, 25, 11, 64, 22, 34, 90].
  • Compare 25 and 11, swap them because 25 > 11: [11, 12, 25, 64, 22, 34, 90].
  • Compare 12 and 22, swap them because 12 < 22: [11, 12, 22, 64, 25, 34, 90].
  • Check the value of swapped: it's True, so repeat the pass through the list.
  1. Iterate through the list for the second pass (from index 0 to 5):
  • Compare 11 and 12, no need to swap because 11 <= 12: [11, 12, 22, 64, 25, 34, 90].
  • Compare 12 and 22, swap them because 12 < 22: [11, 22, 12, 64, 25, 34, 90].
  • Check the value of swapped: it's False, so we can exit the algorithm.

The sorted list is [11, 12, 22, 25, 34, 64, 90].

Common Mistakes

  1. Misunderstanding the flag variable: Some beginners forget to initialize the flag variable or check its value after each pass through the list. This can cause the algorithm to run unnecessarily long passes when the list is already sorted.
  2. Comparing elements out of bounds: Be careful not to compare elements outside the range of the list (e.g., comparing arr[n]). This will result in an IndexError.
  3. Swapping elements incorrectly: It's essential to use the assignment operator (=) when swapping elements, as shown in the example above. Some beginners may accidentally use the addition or subtraction operators instead.
  4. Inefficient implementation: Beginners might implement bubble sort without the flag variable optimization, leading to slower performance on small datasets. The optimized version of the algorithm is presented above.

Practice Questions

  1. Implement bubble sort using a nested loop (without the flag variable optimization). How does its performance compare with the optimized version?
  2. Modify the bubble_sort function to handle negative numbers in the input list.
  3. Write a function that sorts a given list using bubble sort, but only swaps elements if their absolute difference is greater than a specified threshold (e.g., 5).
  4. Implement a recursive version of the bubble sort algorithm. What are its advantages and disadvantages compared to the iterative version?

FAQ

Why do we use the flag variable in bubble sort?

  • The flag variable helps us exit early if no swaps were made during a pass through the list, which indicates that the list is sorted. This optimization reduces the number of unnecessary passes and improves performance on small datasets.

What are some limitations of bubble sort?

  • Bubble sort has poor performance on large datasets due to its quadratic time complexity (O(n^2)). It should be used only when the input data size is small or when performance is not a critical concern.

How can I optimize bubble sort for larger datasets?

  • One way to optimize bubble sort is by using a modified version called "optimized bubble sort" that takes advantage of the flag variable to exit early if no swaps were made during a pass through the list. Another approach is to use more efficient sorting algorithms like quicksort, mergesort, or heapsort for larger datasets.

Can I implement bubble sort in C instead of Python?

  • Yes, you can implement bubble sort in C. The core concept remains the same, but the syntax and implementation details will differ due to differences between the two languages.
Bubble Sort (Python Programming) | Python | XQA Learn