2019-07-01 08:10:18 +00:00
|
|
|
"""
|
|
|
|
Tree_sort algorithm.
|
|
|
|
|
2023-10-16 00:44:10 +00:00
|
|
|
Build a Binary Search Tree and then iterate thru it to get a sorted list.
|
2019-07-01 08:10:18 +00:00
|
|
|
"""
|
2024-03-13 06:52:41 +00:00
|
|
|
|
2023-10-16 00:44:10 +00:00
|
|
|
from __future__ import annotations
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2023-10-16 00:44:10 +00:00
|
|
|
from collections.abc import Iterator
|
|
|
|
from dataclasses import dataclass
|
2018-03-04 02:27:05 +00:00
|
|
|
|
2023-10-16 00:44:10 +00:00
|
|
|
|
|
|
|
@dataclass
|
2022-10-12 22:54:20 +00:00
|
|
|
class Node:
|
2023-10-16 00:44:10 +00:00
|
|
|
val: int
|
|
|
|
left: Node | None = None
|
|
|
|
right: Node | None = None
|
|
|
|
|
|
|
|
def __iter__(self) -> Iterator[int]:
|
|
|
|
if self.left:
|
|
|
|
yield from self.left
|
|
|
|
yield self.val
|
|
|
|
if self.right:
|
|
|
|
yield from self.right
|
|
|
|
|
|
|
|
def __len__(self) -> int:
|
|
|
|
return sum(1 for _ in self)
|
|
|
|
|
|
|
|
def insert(self, val: int) -> None:
|
|
|
|
if val < self.val:
|
|
|
|
if self.left is None:
|
|
|
|
self.left = Node(val)
|
|
|
|
else:
|
|
|
|
self.left.insert(val)
|
|
|
|
elif val > self.val:
|
|
|
|
if self.right is None:
|
|
|
|
self.right = Node(val)
|
|
|
|
else:
|
|
|
|
self.right.insert(val)
|
|
|
|
|
|
|
|
|
|
|
|
def tree_sort(arr: list[int]) -> tuple[int, ...]:
|
|
|
|
"""
|
|
|
|
>>> tree_sort([])
|
|
|
|
()
|
|
|
|
>>> tree_sort((1,))
|
|
|
|
(1,)
|
|
|
|
>>> tree_sort((1, 2))
|
|
|
|
(1, 2)
|
|
|
|
>>> tree_sort([5, 2, 7])
|
|
|
|
(2, 5, 7)
|
|
|
|
>>> tree_sort((5, -4, 9, 2, 7))
|
|
|
|
(-4, 2, 5, 7, 9)
|
|
|
|
>>> tree_sort([5, 6, 1, -1, 4, 37, 2, 7])
|
|
|
|
(-1, 1, 2, 4, 5, 6, 7, 37)
|
2023-10-16 14:17:48 +00:00
|
|
|
|
|
|
|
# >>> tree_sort(range(10, -10, -1)) == tuple(sorted(range(10, -10, -1)))
|
|
|
|
# True
|
2023-10-16 00:44:10 +00:00
|
|
|
"""
|
2018-03-04 02:27:05 +00:00
|
|
|
if len(arr) == 0:
|
2023-10-16 00:44:10 +00:00
|
|
|
return tuple(arr)
|
2022-10-12 22:54:20 +00:00
|
|
|
root = Node(arr[0])
|
2023-10-16 00:44:10 +00:00
|
|
|
for item in arr[1:]:
|
|
|
|
root.insert(item)
|
|
|
|
return tuple(root)
|
2018-03-04 02:27:05 +00:00
|
|
|
|
2019-07-01 08:10:18 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2023-10-16 00:44:10 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
|
|
|
print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }")
|