Coding Bubble Sort in Python

0

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:

my_list = [2, 6, 5, 1, 3, 4]

Step 1: Function Definition

We’ll start by defining a function called bubblesort that takes a list as input:

def bubblesort(my_list):
    # Outer loop for number of passes
    for i in range(len(my_list) – 1, 0, -1):
        # Inner loop for comparisons in each pass
        for j in range(i):
            # Compare adjacent items
            if my_list[j] > my_list[j + 1]:
                # Swap if items are out of order
                temp = my_list[j]
                my_list[j] = my_list[j + 1]
                my_list[j + 1] = temp
    return my_list

Step 2: Understanding the Loops

  • Outer loop (i): Determines the number of passes.

    • First pass: len(my_list) - 1 comparisons

    • Second pass: len(my_list) - 2 comparisons

    • 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

sorted_list = bubblesort([2, 6, 5, 1, 3, 4])
print(sorted_list)

Output:

[1, 2, 3, 4, 5, 6]

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)

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top