Back to: Python Data Structure and Algorithims
Coding Bubble Sort in Python
Now that we understand how Bubble Sort works, let’s write the Python function to implement it.
We’ll use the same example list as before:
Step 1: Function Definition
We’ll start by defining a function called bubblesort that takes a list as input:
Step 2: Understanding the Loops
-
Outer loop (
i): Determines the number of passes.-
First pass:
len(my_list) - 1comparisons -
Second pass:
len(my_list) - 2comparisons -
And so on… until the list is sorted.
-
-
Inner loop (
j): Goes through the list up to the last unsorted element. -
Swap logic: If the current element is greater than the next, swap them using a temporary variable.
Step 3: Step-by-Step Example
Original list: [2, 6, 5, 1, 3, 4]
First pass:
-
Compare 2 and 6 → no swap →
[2, 6, 5, 1, 3, 4] -
Compare 6 and 5 → swap →
[2, 5, 6, 1, 3, 4] -
Compare 6 and 1 → swap →
[2, 5, 1, 6, 3, 4] -
Compare 6 and 3 → swap →
[2, 5, 1, 3, 6, 4] -
Compare 6 and 4 → swap →
[2, 5, 1, 3, 4, 6]
Second pass:
-
Compare 2 and 5 → no swap →
[2, 5, 1, 3, 4, 6] -
Compare 5 and 1 → swap →
[2, 1, 5, 3, 4, 6] -
Compare 5 and 3 → swap →
[2, 1, 3, 5, 4, 6] -
Compare 5 and 4 → swap →
[2, 1, 3, 4, 5, 6]
Third pass:
-
Compare 2 and 1 → swap →
[1, 2, 3, 4, 5, 6] -
Compare 2 and 3 → no swap
-
Compare 3 and 4 → no swap
Fourth pass:
-
Compare 1 and 2 → no swap
-
Compare 2 and 3 → no swap
List is now sorted: [1, 2, 3, 4, 5, 6]
Step 4: Running the Function
Output:
Key Points
-
Bubble Sort compares adjacent elements and swaps if necessary.
-
Largest items “bubble up” to the end in each pass.
-
Time Complexity:
-
Worst-case:
O(n²) -
Best-case:
O(n)(if already sorted)
-
-
Space Complexity:
O(1)(in-place sorting)