22
33
44def binary_search (lst : list [Any ], item : Any , start : int , end : int ) -> int :
5+ """>>> binary_search([1, 3, 5], 4, 0, 2)
6+ 2
7+ >>> binary_search([1, 3, 5], 0, 0, 2)
8+ 0
9+ >>> binary_search([1, 3, 5], 6, 0, 2)
10+ 3
11+
12+ Find the insertion index for ``item`` in a sorted sublist.
13+
14+ It performs a recursive binary search on ``lst`` between indices
15+ ``start`` and ``end`` (inclusive) and returns the index showing
16+ where to insert the item so the list stays sorted.
17+
18+ Args:
19+ lst: A list of comparable items (the sublist from ``start`` to ``end`` must already be sorted).
20+ item: The value to locate an insertion index for.
21+ start: Left-most index of the sorted sublist to search.
22+ end: Right-most index of the sorted sublist to search.
23+
24+ Returns:
25+ The index at which ``item`` should be inserted.
26+ """
527 if start == end :
628 return start if lst [start ] > item else start + 1
729 if start > end :
@@ -17,6 +39,21 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
1739
1840
1941def insertion_sort (lst : list [Any ]) -> list [Any ]:
42+ """>>> insertion_sort([3, 2, 1])
43+ [1, 2, 3]
44+
45+ Return a sorted copy of ``lst`` using insertion sort.
46+
47+ Uses ``binary_search`` to find where to insert each item. The
48+ input list is not modified; a new sorted list is returned.
49+
50+ Args:
51+ lst: The list to sort. A new list is returned; the input list is
52+ not modified in-place.
53+
54+ Returns:
55+ A new list containing the elements of ``lst`` in ascending order.
56+ """
2057 length = len (lst )
2158
2259 for index in range (1 , length ):
@@ -28,6 +65,19 @@ def insertion_sort(lst: list[Any]) -> list[Any]:
2865
2966
3067def merge (left : list [Any ], right : list [Any ]) -> list [Any ]:
68+ """>>> merge([1, 4], [2, 3])
69+ [1, 2, 3, 4]
70+
71+ Merge two sorted lists and return a new sorted list.
72+
73+ Args:
74+ left: A list sorted in ascending order.
75+ right: A list sorted in ascending order.
76+
77+ Returns:
78+ A new list containing all elements from ``left`` and ``right`` in
79+ ascending order.
80+ """
3181 if not left :
3282 return right
3383
@@ -52,6 +102,9 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]:
52102 True
53103 >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1])
54104 True
105+
106+ Sort and return the input using a TimSort-like approach: detect
107+ runs, sort each run with insertion sort, then merge the runs.
55108 """
56109 length = len (lst )
57110 runs , sorted_runs = [], []
0 commit comments