Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Cocktail Sort (or Shaker Sort)

Introduction to Cocktail Sort (or Shaker Sort)

Cocktail Sort, also known as Shaker Sort or Bidirectional Bubble Sort, is a variation of the famous Bubble Sort algorithm. Like Bubble Sort, Cocktail Sort is a simple comparison-based sorting algorithm meant for small datasets. The primary difference between Bubble Sort and Cocktail Sort lies in the traversal of the list. While Bubble Sort traverses the list in one direction, Cocktail Sort traverses the list in both directions, with each pass alternating between left-to-right and right-to-left.

In this lesson, we will discuss the Cocktail Sort algorithm in detail and walk through some real-world examples and scenarios where this algorithm can be effectively applied. We will also provide a step-by-step solution to a real-world problem, along with actual code and high-level comments.

Real-World Examples and Scenarios of Cocktail Sort

Cocktail Sort is best suited for small datasets or datasets that are already partially sorted. Some real-world examples and scenarios where Cocktail Sort can be used effectively include:

  1. Sorting a small list of names in alphabetical order.
  2. Organizing a small list of items by price, weight, or other criteria.
  3. Sorting a small number of students by their grades.
  4. Arranging a list of tasks by priority or deadlines.

Now that we have a better understanding of Cocktail Sort and its real-world applications, let's dive into a specific scenario and generate a technical problem.

Real-World Scenario and Technical Problem

Imagine you are working in a library, and you have been tasked with organizing a small collection of books by their publication dates. For this task, you decide to use the Cocktail Sort algorithm to efficiently sort the books in ascending order of their publication dates.

Problem Statement and Formal Definition

Given a list of books, each with a publication date, sort the list in ascending order of their publication dates using the Cocktail Sort algorithm.

Formally, given a list of books B = {b1, b2, b3, ..., bn}, where each book bi has a publication date di, sort the list B such that for all i < j, di <= dj.

Tying the Problem Statement with the Real-World Scenario

This problem statement is directly tied to the real-world scenario of organizing a library's collection of books by their publication dates. By sorting the list of books in ascending order of their publication dates, we will have successfully organized the library's collection as per the given task.

Solution to the Problem

To solve this problem using Cocktail Sort, we will perform the following steps:

  1. Define a function, cocktail_sort, that takes the list of books as input and returns the sorted list.
  2. Initialize two pointers, left and right, to represent the current range of the unsorted list.
  3. Traverse the list from left to right, comparing consecutive books and swapping them if they are out of order.
  4. Update the right pointer to the last position where a swap occurred.
  5. Traverse the list from right to left, comparing consecutive books and swapping them if they are out of order.
  6. Update the left pointer to the first position where a swap occurred.
  7. Repeat steps 3-6 until the left and right pointers meet, indicating that the list is now sorted.

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

Let's now solve the problem step by step using the library books scenario:

  1. Create a list of books with their publication dates.
  2. Implement the cocktail_sort function to sort the list of books.
  3. Call the cocktail_sort function with the actual list of books as input.
  4. Print the sorted list of books.

Actual Code Solution with High-Level Comments

# Define the Cocktail Sort function
def cocktail_sort(books):
    n = len(books)
    left = 0
    right = n - 1
    swapped = True

    while swapped:
        swapped = False

        # Traverse the list from left to right
        for i in range(left, right):
            if books[i]["date"] > books[i + 1]["date"]:
                books[i], books[i + 1] = books[i + 1], books[i]
                swapped = True

        # If no swaps occurred, the list is already sorted
        if not swapped:
            break

        # Update the right pointer
        right -= 1

        # Traverse the list from right to left
        for i in range(right, left, -1):
            if books[i]["date"] < books[i - 1]["date"]:
                books[i], books[i - 1] = books[i - 1], books[i]
                swapped = True

        # Update the left pointer
        left += 1

    return books

# Create a list of books with their publication dates
books = [
    {"title": "Book A", "date": 1987},
    {"title": "Book B", "date": 2005},
    {"title": "Book C", "date": 1995},
    {"title": "Book D", "date": 2010},
    {"title": "Book E", "date": 1976},
]

# Call the Cocktail Sort function with the list of books
sorted_books = cocktail_sort(books)

# Print the sorted list of books
for book in sorted_books:
    print(book["title"], book["date"])

Explanation of the Code Solution

The cocktail_sort function sorts the list of books by their publication dates using the Cocktail Sort algorithm. The function first initializes the left and right pointers and sets a swapped flag to True. The function then enters a while loop, which continues until no swaps occur during a complete traversal of the list.

In each iteration of the while loop, the function traverses the list from left to right, comparing consecutive books and swapping them if their publication dates are out of order. It then updates the right pointer to the last position where a swap occurred.

Next, the function traverses the list from right to left, again comparing consecutive books and swapping them if their publication dates are out of order. It then updates the left pointer to the first position where a swap occurred.

The while loop continues until the left and right pointers meet, indicating that the list is now sorted. The function then returns the sorted list of books.

Applying the Solution to Other Real-World Problems

The Cocktail Sort algorithm can be applied to other real-world problems that involve sorting small or partially sorted datasets. By modifying the comparison criteria in the code, the algorithm can be adapted to sort lists based on different attributes, such as names, prices, weights, grades, or priorities. This makes the Cocktail Sort a versatile and straightforward sorting algorithm for a wide range of applications.