Skip to content

Commit bc39523

Browse files
committed
added time complexity
1 parent f0a24e1 commit bc39523

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

sorts/tim_sort.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
2424
2525
Returns:
2626
The index at which ``item`` should be inserted.
27+
28+
Complexity:
29+
Time: ``O(log n)`` for the searched sublist.
30+
Space: ``O(log n)`` due to recursion depth.
2731
"""
2832
if start == end:
2933
return start if lst[start] > item else start + 1
@@ -54,6 +58,11 @@ def insertion_sort(lst: list[Any]) -> list[Any]:
5458
5559
Returns:
5660
A new list containing the elements of ``lst`` in ascending order.
61+
62+
Complexity:
63+
Time: ``O(n^2)`` in the worst case because each insertion may
64+
shift many elements.
65+
Space: ``O(n)`` for the reconstructed list copies.
5766
"""
5867
length = len(lst)
5968

@@ -78,6 +87,10 @@ def merge(left: list[Any], right: list[Any]) -> list[Any]:
7887
Returns:
7988
A new list containing all elements from ``left`` and ``right`` in
8089
ascending order.
90+
91+
Complexity:
92+
Time: ``O(n + m)`` where ``n`` and ``m`` are the input lengths.
93+
Space: ``O(n + m)`` because recursive slicing creates new lists.
8194
"""
8295
if not left:
8396
return right
@@ -106,6 +119,10 @@ def tim_sort(lst: list[Any] | tuple[Any, ...] | str) -> list[Any]:
106119
107120
Sort and return the input using a TimSort-like approach: detect
108121
runs, sort each run with insertion sort, then merge the runs.
122+
123+
Complexity:
124+
Time: ``O(n log n)`` in the common case.
125+
Space: ``O(n)`` for the extra lists used during sorting.
109126
"""
110127
length = len(lst)
111128
runs, sorted_runs = [], []

0 commit comments

Comments
 (0)