Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions sorts/odd_even_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,22 @@
https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
"""

from typing import Protocol

def odd_even_sort(input_list: list) -> list:

class Comparable(Protocol):
def __lt__(self, other: object, /) -> bool: ...


def odd_even_sort[T: Comparable](input_list: list[T]) -> list[T]:
"""
Sort input with odd even sort.

This algorithm uses the same idea of bubblesort,
but by first dividing in two phase (odd and even).
Originally developed for use on parallel processors
with local interconnections.
:param collection: mutable ordered sequence of elements
:param input_list: mutable ordered sequence of comparable elements
:return: same collection in ascending order
Examples:
>>> odd_even_sort([5 , 4 ,3 ,2 ,1])
Expand All @@ -24,18 +30,26 @@ def odd_even_sort(input_list: list) -> list:
[-10, -1, 2, 10]
>>> odd_even_sort([1 ,2 ,3 ,4])
[1, 2, 3, 4]
>>> odd_even_sort(["c", "a", "b"])
['a', 'b', 'c']
>>> odd_even_sort([2.5, -1.0, 0.0])
[-1.0, 0.0, 2.5]
>>> odd_even_sort([1, "a"]) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: ...
"""
is_sorted = False
while is_sorted is False: # Until all the indices are traversed keep looping
is_sorted = True
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
if input_list[i + 1] < input_list[i]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
is_sorted = False

for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
if input_list[i + 1] < input_list[i]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
is_sorted = False
Expand Down
1 change: 1 addition & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def test_sort_matches_builtin(sort, case) -> None:
gnome_sort,
insertion_sort,
merge_sort,
odd_even_sort,
selection_sort,
],
ids=lambda f: f.__name__,
Expand Down
Loading