Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Odd-Even Sort (or Brick Sort)

Introduction

Odd-Even Sort, also known as Brick Sort, is a relatively simple comparison-based sorting algorithm. It works by iteratively comparing and swapping adjacent elements in an array or list. The algorithm divides the elements into two groups - odd-indexed and even-indexed elements. It then sorts the odd-indexed elements relative to each other and the even-indexed elements relative to each other. This process is repeated until the entire list is sorted.

In this lesson, we will explore the Odd-Even Sort algorithm, its real-world applications, and walk through a sample problem and its solution with actual code.

Real-world Examples and Scenarios of Odd-Even Sort

Odd-Even Sort is not the most efficient sorting algorithm, but it has some niche applications in certain scenarios. Some real-world examples and scenarios where Odd-Even Sort can be used are:

Sorting small datasets: For small lists or arrays, the difference in efficiency between Odd-Even Sort and more advanced algorithms like Quick Sort or Merge Sort may not be significant. In such cases, the simplicity of Odd-Even Sort can be an advantage.

Parallel computing: Odd-Even Sort can be easily parallelized, making it suitable for use in parallel computing environments. This is because the odd and even phases of the algorithm can be executed independently of each other.

Teaching programming: Odd-Even Sort is a simple algorithm that can help beginners understand the concepts of sorting and algorithms. It can be a good starting point before moving on to more complex algorithms.

Real-world Scenario: Sorting Students by GPA

Let's consider a real-world scenario in which we need to sort a list of students based on their GPA. The school has a list of students, and they need to be sorted in ascending order based on their GPA so that the school can identify the top and bottom performers.

Problem Statement

We are given a list of students, where each student is represented as an object with the following attributes:

  • name: The name of the student (a string)
  • gpa: The GPA of the student (a float)

Our task is to sort the list of students in ascending order based on their GPA using the Odd-Even Sort algorithm.

Formal Definition

Given a list students of n objects, where each object has attributes name and gpa, we need to find a permutation of the list sorted_students such that for all i and j where 0 <= i < j < n, the gpa of sorted_students[i] is less than or equal to the gpa of sorted_students[j].

Tying the Problem Statement with the Real-world Scenario

In our real-world scenario, we have a list of students that we need to sort based on their GPA. The problem statement provides us with a clear goal: to sort the list using the Odd-Even Sort algorithm. By solving this problem, we will be able to identify the top and bottom performers in the school.

Solution to the Problem

To solve this problem, we will implement the Odd-Even Sort algorithm in Python and use it to sort our list of students. Let's break down the algorithm into steps:

  1. Iterate through the list, comparing and swapping adjacent odd-indexed elements with their even-indexed neighbors if they are out of order.
  2. Iterate through the list again, comparing and swapping adjacent even-indexed elements with their odd-indexed neighbors if they are out of order.
  3. Repeat steps 1 and 2 until the list is fully sorted.

Actual Code Solution with High-level Comments

def odd_even_sort(students):
    # Get the length of the list
    n = len(students)

    # Initialize a variable to keep track of whether we have made any swaps in the current iteration
    swapped = True

    # Continue iterating until no swaps are made in a full pass
    while swapped:
        swapped = False

        # Iterate through odd-indexed elements and swap if necessary
        for i in range(1, n-1, 2):
            if students[i].gpa > students[i+1].gpa:
                students[i], students[i+1] = students[i+1], students[i]
                swapped = True

        # Iterate through even-indexed elements and swap if necessary
        for i in range(0, n-1, 2):
            if students[i].gpa > students[i+1].gpa:
                students[i], students[i+1] = students[i+1], students[i]
                swapped = True

    return students

Calling the Function with Actual Values

Now let's create some sample student data and call our odd_even_sort function to sort the students by their GPA.

class Student:
    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa

    def __repr__(self):
        return f"{self.name}: {self.gpa}"

# Sample list of students
students = [
    Student("Alice", 3.5),
    Student("Bob", 2.7),
    Student("Charlie", 3.9),
    Student("David", 3.2),
    Student("Eve", 4.0)
]

# Sort the students using odd_even_sort
sorted_students = odd_even_sort(students)

# Print the sorted students
print(sorted_students)

This should output the following sorted list of students:

[Bob: 2.7, David: 3.2, Alice: 3.5, Charlie: 3.9, Eve: 4.0]

Explanation of the Code Solution

Our implementation of the Odd-Even Sort algorithm in Python starts by getting the length of the input list students and initializing a variable swapped to True. This variable is used to keep track of whether we have made any swaps in the current iteration.

We then enter a while loop that continues until no swaps are made in a full pass through the list. Inside the loop, we first iterate through the odd-indexed elements and compare each element with its even-indexed neighbor. If the odd-indexed element has a greater GPA than its neighbor, we swap them and set swapped to True. We then do the same for the even-indexed elements.

Once the loop completes without making any swaps, we know that the list is fully sorted, and we return the sorted list of students.

Solving Other Real-world Problems with Odd-Even Sort

The solution we have provided for sorting students by their GPA can also be applied to other similar real-world problems. For example, we could use the same algorithm to sort a list of employees by their performance metrics or a list of products by their prices.

By understanding the Odd-Even Sort algorithm and its implementation in Python, we can easily adapt the solution to other scenarios that require sorting a list of objects based on some attribute.

In conclusion, the Odd-Even Sort algorithm, while not the most efficient, can be a simple and effective solution for certain real-world problems. Its simplicity and potential for parallelization make it a useful tool in some scenarios, especially for small datasets and introductory programming lessons.