Skip to content

Commit 8af4051

Browse files
author
Shreya
committed
Add docstrings to helper functions in tim_sort
1 parent e3b01ec commit 8af4051

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

sorts/tim_sort.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,30 @@
1+
"""
2+
A pure Python implementation of the Tim Sort algorithm.
3+
4+
For doctests run following command:
5+
python -m doctest -v tim_sort.py
6+
or
7+
python3 -m doctest -v tim_sort.py
8+
9+
For manual testing run:
10+
python tim_sort.py
11+
or
12+
python3 tim_sort.py
13+
"""
14+
115
from typing import Any
216

317

418
def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
19+
"""
20+
Find the insertion position of an item in a sorted list.
21+
22+
:param lst: A sorted list of comparable items.
23+
:param item: The item to insert.
24+
:param start: The starting index of the search range.
25+
:param end: The ending index of the search range.
26+
:return: The index where the item should be inserted.
27+
"""
528
if start == end:
629
return start if lst[start] > item else start + 1
730
if start > end:
@@ -17,6 +40,12 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
1740

1841

1942
def insertion_sort(lst: list[Any]) -> list[Any]:
43+
"""
44+
Sort a list using the insertion sort algorithm.
45+
46+
:param lst: A list of comparable items.
47+
:return: The sorted list.
48+
"""
2049
length = len(lst)
2150

2251
for index in range(1, length):
@@ -28,6 +57,13 @@ def insertion_sort(lst: list[Any]) -> list[Any]:
2857

2958

3059
def merge(left: list[Any], right: list[Any]) -> list[Any]:
60+
"""
61+
Merge two sorted lists into a single sorted list.
62+
63+
:param left: The left sorted list.
64+
:param right: The right sorted list.
65+
:return: A merged sorted list.
66+
"""
3167
if not left:
3268
return right
3369

@@ -76,6 +112,9 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]:
76112

77113

78114
def main():
115+
"""
116+
Run a simple example of the Tim Sort algorithm.
117+
"""
79118
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
80119
sorted_lst = tim_sort(lst)
81120
print(sorted_lst)

0 commit comments

Comments
 (0)