Python/sorts/odd_even_transposition_single_threaded.py

34 lines
888 B
Python
Raw Normal View History

"""
2020-06-25 07:48:52 +00:00
Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
This is a non-parallelized implementation of odd-even transpostiion sort.
Normally the swaps in each set happen simultaneously, without that the algorithm
is no better than bubble sort.
"""
2019-10-05 05:14:13 +00:00
2020-06-25 07:48:52 +00:00
def odd_even_transposition(arr: list) -> list:
"""
2020-06-25 07:48:52 +00:00
>>> odd_even_transposition([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
2020-06-25 07:48:52 +00:00
>>> odd_even_transposition([13, 11, 18, 0, -1])
[-1, 0, 11, 13, 18]
2020-06-25 07:48:52 +00:00
>>> odd_even_transposition([-.1, 1.1, .1, -2.9])
[-2.9, -0.1, 0.1, 1.1]
"""
2020-06-25 07:48:52 +00:00
arr_size = len(arr)
for _ in range(arr_size):
for i in range(_ % 2, arr_size - 1, 2):
if arr[i + 1] < arr[i]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
arr = list(range(10, 0, -1))
2020-06-25 07:48:52 +00:00
print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")