Skip to content

Commit 18a0ab1

Browse files
dajiaohuangclaude
andcommitted
docs: add docstrings to tim_sort helper functions
Add docstrings with doctests to binary_search(), insertion_sort(), merge(), and main() in sorts/tim_sort.py for consistency with the already-documented tim_sort(). Fixes #14773 Co-Authored-By: Claude <noreply@anthropic.com>
1 parent e3b01ec commit 18a0ab1

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

sorts/tim_sort.py

Lines changed: 32 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+
"""Find the insertion position for *item* in a sorted sublist using binary search.
6+
7+
Returns the index where *item* should be inserted to maintain sorted order
8+
in ``lst[start:end+1]``.
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,16 @@ 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 a list using binary insertion sort.
33+
34+
For each element, use :func:`binary_search` to find its correct position
35+
in the already-sorted prefix, then insert it there.
36+
37+
>>> insertion_sort([3, 1, 2])
38+
[1, 2, 3]
39+
>>> insertion_sort([5, 9, 10, 3, -4])
40+
[-4, 3, 5, 9, 10]
41+
"""
2042
length = len(lst)
2143

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

2951

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

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

77108

78109
def main():
110+
"""Run a demo of Timsort on a sample list and print the result."""
79111
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
80112
sorted_lst = tim_sort(lst)
81113
print(sorted_lst)

0 commit comments

Comments
 (0)