Skip to content

Commit 971331b

Browse files
committed
Make bitonic sort support comparable items
1 parent feceadf commit 971331b

1 file changed

Lines changed: 25 additions & 3 deletions

File tree

‎sorts/bitonic_sort.py‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,14 @@
66

77
from __future__ import annotations
88

9+
from typing import Protocol
910

10-
def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:
11+
12+
class Comparable(Protocol):
13+
def __lt__(self, other: object, /) -> bool: ...
14+
15+
16+
def comp_and_swap[T: Coparable](array: list[T], index1: int, index2: int, direction: int) -> None:
1117
"""Compare the value at given index1 and index2 of the array and swap them as per
1218
the given direction.
1319
@@ -38,7 +44,7 @@ def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) ->
3844
array[index1], array[index2] = array[index2], array[index1]
3945

4046

41-
def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:
47+
def bitonic_merge[T: Comparable](array: list[T], low: int, length: int, direction: int) -> None:
4248
"""
4349
It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in
4450
descending if direction = 0.
@@ -62,7 +68,7 @@ def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> No
6268
bitonic_merge(array, low + middle, middle, direction)
6369

6470

65-
def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:
71+
def bitonic_sort[T: Comparable](array: list[T], low: int, length: int, direction: int) -> None:
6672
"""
6773
This function first produces a bitonic sequence by recursively sorting its two
6874
halves in opposite sorting orders, and then calls bitonic_merge to make them in the
@@ -76,6 +82,22 @@ def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> Non
7682
>>> bitonic_sort(arr, 0, 8, 0)
7783
>>> arr
7884
[145, 92, 34, 12, 0, -23, -121, -167]
85+
86+
>>> arr = ["banana", "apple", "cherry","date"]
87+
>>> bitonic_sort(arr, 0, 4, 1)
88+
>>> arr
89+
['apple', 'banana', 'cherry', 'date']
90+
91+
>>> arr = [3, 1.5, 2, 4.5]
92+
>>> bitonic_sort(arr, 0, 4, 1)
93+
>>> arr
94+
[1.5, 2, 3, 4.5]
95+
96+
>>> arr = [1, "two", 3, "four"]
97+
>>> bitonic_sort(arr, 0, 4, 1)
98+
Traceback (most recent call last):
99+
...
100+
TypeError: '>' not supported between instances of 'int' and 'str'
79101
"""
80102
if length > 1:
81103
middle = int(length / 2)

0 commit comments

Comments
 (0)