codon/stdlib/internal/sort.codon

60 lines
1.6 KiB
Python
Raw Normal View History

2022-01-24 15:17:01 +08:00
# (c) 2022 Exaloop Inc. All rights reserved.
2021-09-28 02:02:44 +08:00
from algorithms.pdqsort import pdq_sort_inplace
from algorithms.insertionsort import insertion_sort_inplace
from algorithms.heapsort import heap_sort_inplace
from algorithms.qsort import qsort_inplace
2022-01-27 00:30:18 +08:00
from algorithms.timsort import tim_sort_inplace
2021-09-28 02:02:44 +08:00
2022-01-24 15:17:01 +08:00
def sorted(
2021-09-28 02:02:44 +08:00
v: Generator[T],
2022-01-24 15:17:01 +08:00
key=Optional[int](),
2021-09-28 02:02:44 +08:00
algorithm: Optional[str] = None,
reverse: bool = False,
2022-01-24 15:17:01 +08:00
T: type,
) -> List[T]:
2021-09-28 02:02:44 +08:00
"""
Return a sorted list of the elements in v
"""
newlist = [a for a in v]
if not isinstance(key, Optional):
newlist.sort(key, algorithm, reverse)
else:
newlist.sort(algorithm=algorithm, reverse=reverse)
return newlist
2022-01-24 15:17:01 +08:00
def _sort_list(
self: List[T], key: Callable[[T], S], algorithm: str, T: type, S: type
2022-02-16 23:51:16 +08:00
):
2022-01-27 00:30:18 +08:00
if algorithm == "tim":
tim_sort_inplace(self, key)
elif algorithm == "pdq":
2021-09-28 02:02:44 +08:00
pdq_sort_inplace(self, key)
2022-01-24 15:17:01 +08:00
elif algorithm == "insertion":
2021-09-28 02:02:44 +08:00
insertion_sort_inplace(self, key)
2022-01-24 15:17:01 +08:00
elif algorithm == "heap":
2021-09-28 02:02:44 +08:00
heap_sort_inplace(self, key)
2022-01-24 15:17:01 +08:00
elif algorithm == "quick":
2021-09-28 02:02:44 +08:00
qsort_inplace(self, key)
else:
2022-02-16 23:51:16 +08:00
raise ValueError(f"Algorithm '{algorithm}' does not exist")
2021-09-28 02:02:44 +08:00
2022-01-24 15:17:01 +08:00
2021-09-28 02:02:44 +08:00
@extend
class List:
def sort(
self,
2022-01-24 15:17:01 +08:00
key=Optional[int](),
2021-09-28 02:02:44 +08:00
algorithm: Optional[str] = None,
2022-01-24 15:17:01 +08:00
reverse: bool = False,
2022-02-16 23:51:16 +08:00
):
algorithm: str = algorithm if algorithm is not None else "tim"
2021-09-28 02:02:44 +08:00
if isinstance(key, Optional):
2022-02-16 23:51:16 +08:00
_sort_list(self, lambda x: x, algorithm)
2021-09-28 02:02:44 +08:00
else:
2022-02-16 23:51:16 +08:00
_sort_list(self, key, algorithm)
2021-09-28 02:02:44 +08:00
if reverse:
self.reverse()