Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sorts/gnome_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@


if __name__ == "__main__":
import doctest

Check failure on line 55 in sorts/gnome_sort.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W293)

sorts/gnome_sort.py:55:1: W293 Blank line contains whitespace help: Remove whitespace from blank line
doctest.testmod()

Check failure on line 57 in sorts/gnome_sort.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (W293)

sorts/gnome_sort.py:57:1: W293 Blank line contains whitespace help: Remove whitespace from blank line
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(gnome_sort(unsorted))
39 changes: 39 additions & 0 deletions sorts/tim_sort.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,30 @@
"""
A pure Python implementation of the Tim Sort algorithm.

For doctests run following command:
python -m doctest -v tim_sort.py
or
python3 -m doctest -v tim_sort.py

For manual testing run:
python tim_sort.py
or
python3 tim_sort.py
"""

from typing import Any


def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:
"""
Find the insertion position of an item in a sorted list.

:param lst: A sorted list of comparable items.
:param item: The item to insert.
:param start: The starting index of the search range.
:param end: The ending index of the search range.
:return: The index where the item should be inserted.
"""
if start == end:
return start if lst[start] > item else start + 1
if start > end:
Expand All @@ -17,6 +40,12 @@ def binary_search(lst: list[Any], item: Any, start: int, end: int) -> int:


def insertion_sort(lst: list[Any]) -> list[Any]:
"""
Sort a list using the insertion sort algorithm.

:param lst: A list of comparable items.
:return: The sorted list.
"""
length = len(lst)

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


def merge(left: list[Any], right: list[Any]) -> list[Any]:
"""
Merge two sorted lists into a single sorted list.

:param left: The left sorted list.
:param right: The right sorted list.
:return: A merged sorted list.
"""
if not left:
return right

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


def main():
"""
Run a simple example of the Tim Sort algorithm.
"""
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
sorted_lst = tim_sort(lst)
print(sorted_lst)
Expand Down
Loading