Skip to content

Commit b125dab

Browse files
author
deepshekhardas
committed
docs: add missing docstrings to tim_sort helpers
Add docstrings with doctests to binary_search, insertion_sort, merge, and main in sorts/tim_sort.py, making helpers consistent with the already-documented tim_sort. Fixes #14773
1 parent f5988cc commit b125dab

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

sorts/tim_sort.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22

33

44
def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
5+
"""Return the insertion index for item in sorted lst[start:end+1].
6+
7+
Uses binary search to find where item should be inserted to keep
8+
the sublist sorted. Used by insertion_sort.
9+
10+
>>> binary_search([1, 3, 5, 7], 4, 0, 3)
11+
2
12+
>>> binary_search([1, 3, 5, 7], 0, 0, 3)
13+
0
14+
>>> binary_search([1, 3, 5, 7], 8, 0, 3)
15+
4
16+
"""
517
if start == end:
618
return start if lst[start] > item else start + 1
719
if start > end:
@@ -17,6 +29,15 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
1729

1830

1931
def insertion_sort(lst: list[Any]) -> list[Any]:
32+
"""Sort lst using insertion sort with binary_search for position.
33+
34+
>>> insertion_sort([3, 1, 2])
35+
[1, 2, 3]
36+
>>> insertion_sort([5, 9, 10, 3, -4])
37+
[-4, 3, 5, 9, 10]
38+
>>> insertion_sort([])
39+
[]
40+
"""
2041
length = len(lst)
2142

2243
for index in range(1, length):
@@ -28,6 +49,15 @@ def insertion_sort(lst: list[Any]) -> list[Any]:
2849

2950

3051
def merge(left: list[Any], right: list[Any]) -> list[Any]:
52+
"""Merge two sorted lists into a single sorted list.
53+
54+
>>> merge([1, 3, 5], [2, 4, 6])
55+
[1, 2, 3, 4, 5, 6]
56+
>>> merge([], [1, 2])
57+
[1, 2]
58+
>>> merge([1, 2], [])
59+
[1, 2]
60+
"""
3161
if not left:
3262
return right
3363

@@ -76,6 +106,7 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]:
76106

77107

78108
def main():
109+
"""Demonstrate tim_sort on a sample list."""
79110
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
80111
sorted_lst = tim_sort(lst)
81112
print(sorted_lst)

0 commit comments

Comments
 (0)