Skip to content

Commit 469f44f

Browse files
authored
Add doctests for adaptive_merge_sort
Removed print statements for initial sequence, sorted sequence, sorting steps, and after merge.
1 parent 2471451 commit 469f44f

1 file changed

Lines changed: 12 additions & 16 deletions

File tree

‎sorts/adaptive_merge_sort.py‎

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,22 @@ def __lt__(self, other: object, /) -> bool: ...
66

77

88
def adaptive_merge_sort[T: Comparable](sequence: list[T]) -> list[T]:
9+
"""
10+
Sort a sequence using adaptive merge sort.
11+
12+
>>> adaptive_merge_sort([4, 3, 1, 2])
13+
[1, 2, 3, 4]
14+
>>> adaptive_merge_sort(["banana", "apple", "cherry"])
15+
["apple", "banana", "cherry"]
16+
>>> adaptive_merge_sort([1, "apple"])
17+
Traceback (most recent call last):
18+
TypeError: '<' not supported between instances of 'str' and 'int'
19+
"""
920
if len(sequence) < 2:
1021
return sequence
1122

1223
aux = sequence[:]
13-
print(f"Initial sequence: {sequence}")
1424
adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1)
15-
print(f"Sorted sequence: {sequence}")
1625
return sequence
1726

1827

@@ -23,13 +32,11 @@ def adaptive_merge_sort_helper[T: Comparable](
2332
return
2433

2534
mid = (low + high) // 2
26-
print(f"Sorting: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]")
2735

2836
adaptive_merge_sort_helper(aux, array, low, mid)
2937
adaptive_merge_sort_helper(aux, array, mid + 1, high)
3038

3139
if not array[mid + 1] < array[mid]:
32-
print(f"Skipping merge as array[{mid}] <= array[{mid + 1}]")
3340
array[low : high + 1] = aux[low : high + 1]
3441
return
3542

@@ -39,9 +46,8 @@ def adaptive_merge_sort_helper[T: Comparable](
3946
def merge[T: Comparable](
4047
array: list[T], aux: list[T], low: int, mid: int, high: int
4148
) -> None:
42-
print(f"Merging: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]")
43-
4449
i, j = low, mid + 1
50+
4551
for k in range(low, high + 1):
4652
if i > mid or j > high:
4753
if i > mid:
@@ -59,13 +65,3 @@ def merge[T: Comparable](
5965

6066
for k in range(low, high + 1):
6167
array[k] = aux[k]
62-
63-
print(f"After merge: {array[low : high + 1]}")
64-
65-
66-
# Example usage
67-
if __name__ == "__main__":
68-
print(adaptive_merge_sort([4, 3, 1, 2]))
69-
# Example usage
70-
if __name__ == "__main__":
71-
print(adaptive_merge_sort([4, 3, 1, 2]))

0 commit comments

Comments
 (0)