Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Bubble Sort

Introduction to Bubble Sort

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 algorithm continues to pass through the list until it makes a pass with no swaps. The name "bubble sort" comes from the fact that smaller elements "bubble" to the top of the list.

Bubble sort has a worst-case and average time complexity of O(n^2) where n is the number of items being sorted. Despite its poor time complexity, bubble sort is easy to understand and implement, which makes it a good choice for educational purposes and small datasets.

Real-World Examples of Bubble Sort

Although bubble sort is not the most efficient sorting algorithm, it can still be used in some real-world scenarios where simplicity and ease of implementation are more important than speed. Some examples include:

  1. Sorting small datasets: Bubble sort can be used to sort small datasets when the computational power is limited or the dataset does not require frequent sorting.
  2. Teaching programming concepts: Bubble sort is a great way to teach beginners about algorithms, loops, and comparisons in programming.
  3. Sorting simple data structures: When there is a simple data structure such as a small list or an array, bubble sort can be used to sort the data.

Real-World Scenario: Sorting Student Test Scores

Consider a scenario where a teacher has a list of students and their test scores. The teacher wants to sort the students based on their test scores in ascending order. In this case, bubble sort can be used to sort the list of students and their test scores.

Problem Statement and Formal Definition

Given a list of students and their test scores, sort the list in ascending order of test scores using the bubble sort algorithm.

Input: A list of tuples, where each tuple contains a student's name and their test score. The list is unsorted.

[
  ("Alice", 78),
  ("Bob", 85),
  ("Charlie", 92),
  ("Diana", 88),
  ("Eva", 76)
]

Output: A list of tuples with the same students and test scores, sorted in ascending order of test scores.

[
  ("Eva", 76),
  ("Alice", 78),
  ("Bob", 85),
  ("Diana", 88),
  ("Charlie", 92)
]

Tying the Problem Statement to the Real-World Scenario

Sorting the list of student test scores will allow the teacher to easily identify the highest and lowest scores, as well as the overall performance of the class. By using bubble sort, the teacher can sort the list without needing a complex algorithm or extensive computational resources.

Solution to the Problem

To solve this problem using bubble sort, we will perform the following steps:

  1. Start at the beginning of the list.
  2. Compare the test score of the current student with the test score of the next student.
  3. If the current student's test score is higher than the next student's test score, swap their positions in the list.
  4. Move to the next student and repeat steps 2-3 until the end of the list is reached.
  5. After reaching the end of the list, start again at the beginning of the list and repeat steps 1-4.
  6. Continue this process until a pass through the list is made without any swaps.

Step-by-Step Solution with the Real-World Scenario

  1. Start at the beginning of the list. The first student is Alice with a test score of 78.
  2. Compare Alice's test score (78) with the next student, Bob's test score (85).
  3. Since Alice's test score is not higher than Bob's test score, no swap is needed.
  4. Move to the next student, Bob, and compare his test score (85) with the next student, Charlie's test score (92). No swap is needed.
  5. Continue this process until the end of the list is reached.
  6. After reaching the end of the list, start again at the beginning of the list and repeat steps 1-5 until a pass through the list is made with no swaps.

Actual Code Solution with High-Level Comments

def bubble_sort(student_scores):
    n = len(student_scores)
    # Repeat until no swaps are needed.
    for i in range(n):
        # Flag to check if any swaps occurred in this pass.
        swapped = False
        # Iterate through the unsorted part of the list.
        for j in range(0, n-i-1):
            # Compare test scores of adjacent students.
            if student_scores[j][1] > student_scores[j+1][1]:
                # Swap the students if they are in the wrong order.
                student_scores[j], student_scores[j+1] = student_scores[j+1], student_scores[j]
                # Set the flag to True, indicating a swap occurred.
                swapped = True
        # If no swaps occurred in this pass, the list is sorted.
        if not swapped:
            break
    return student_scores

Calling the Function with Actual Values

students = [
  ("Alice", 78),
  ("Bob", 85),
  ("Charlie", 92),
  ("Diana", 88),
  ("Eva", 76)
]

sorted_students = bubble_sort(students)
print(sorted_students)

Output:

[
  ("Eva", 76),
  ("Alice", 78),
  ("Bob", 85),
  ("Diana", 88),
  ("Charlie", 92)
]

Explanation of the Code Solution

The bubble_sort function takes a list of student scores as its input. The function starts by calculating the length of the list (n) and initializing a flag called "swapped" to False. The function then iterates through the list, comparing the test scores of adjacent students. If the current student's test score is higher than the next student's test score, the two students are swapped, and the "swapped" flag is set to True. After each pass through the list, the function checks if the "swapped" flag is still False. If it is, that means the list is sorted, and the function can return the sorted list.

How the Solution Can Solve Other Real-World Problems

The bubble sort algorithm can be applied to other real-world problems that involve sorting data, such as:

  1. Sorting a list of products by their prices in an online store.
  2. Organizing a list of tasks by their deadlines in a project management tool.
  3. Sorting a list of emails by their timestamps in an email client.

By understanding how the bubble sort algorithm works and implementing it in a programming language, you can use it to solve various sorting problems in real-world applications.