sorts.cocktail_shaker_sort

An implementation of the cocktail shaker sort algorithm in pure Python.

https://en.wikipedia.org/wiki/Cocktail_shaker_sort

Attributes

user_input

Classes

Comparable

Base class for protocol classes.

Functions

cocktail_shaker_sort(→ list[T])

Sorts a list using the Cocktail Shaker Sort algorithm.

Module Contents

class sorts.cocktail_shaker_sort.Comparable

Bases: Protocol

Base class for protocol classes.

Protocol classes are defined as:

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing).

For example:

class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check

See PEP 544 for details. Protocol classes decorated with @typing.runtime_checkable act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes can be generic, they are defined as:

class GenProto[T](Protocol):
    def meth(self) -> T:
        ...
__lt__(other: object, /) bool
sorts.cocktail_shaker_sort.cocktail_shaker_sort[T: Comparable](arr: list[T]) list[T]

Sorts a list using the Cocktail Shaker Sort algorithm.

Parameters:

arr – List of elements to be sorted.

Returns:

Sorted list.

>>> cocktail_shaker_sort([4, 5, 2, 1, 2])
[1, 2, 2, 4, 5]
>>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11])
[-4, 0, 1, 2, 5, 11]
>>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2])
[-2.4, 0.1, 2.2, 4.4]
>>> cocktail_shaker_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
>>> cocktail_shaker_sort([-4, -5, -24, -7, -11])
[-24, -11, -7, -5, -4]
>>> cocktail_shaker_sort(["elderberry", "banana", "date", "apple", "cherry"])
['apple', 'banana', 'cherry', 'date', 'elderberry']
>>> cocktail_shaker_sort((-4, -5, -24, -7, -11))
Traceback (most recent call last):
    ...
TypeError: 'tuple' object does not support item assignment
>>> cocktail_shaker_sort([1, "a"])
Traceback (most recent call last):
    ...
TypeError: ...
sorts.cocktail_shaker_sort.user_input