22
33
44def binary_search (lst : list [Any ], item : Any , start : int , end : int ) -> int :
5+ """
6+ Return the index where ``item`` should be inserted in a sorted list.
7+
8+ Uses binary search to locate the insertion position between
9+ ``start`` and ``end`` while maintaining sorted order.
10+ """
11+
512 if start == end :
613 return start if lst [start ] > item else start + 1
714 if start > end :
@@ -17,6 +24,13 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
1724
1825
1926def insertion_sort (lst : list [Any ]) -> list [Any ]:
27+ """
28+ Sort a list using the insertion sort algorithm.
29+
30+ Each element is inserted into its correct position in the already
31+ sorted portion of the list using binary search.
32+ """
33+
2034 length = len (lst )
2135
2236 for index in range (1 , length ):
@@ -28,6 +42,13 @@ def insertion_sort(lst: list[Any]) -> list[Any]:
2842
2943
3044def merge (left : list [Any ], right : list [Any ]) -> list [Any ]:
45+ """
46+ Merge two sorted lists into a single sorted list.
47+
48+ Recursively combines elements from both input lists while
49+ preserving sorted order.
50+ """
51+
3152 if not left :
3253 return right
3354
@@ -76,6 +97,10 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]:
7697
7798
7899def main ():
100+ """
101+ Run a simple demonstration of the Tim Sort algorithm.
102+ """
103+
79104 lst = [5 , 9 , 10 , 3 , - 4 , 5 , 178 , 92 , 46 , - 18 , 0 , 7 ]
80105 sorted_lst = tim_sort (lst )
81106 print (sorted_lst )
0 commit comments