1
0
mirror of https://github.com/exaloop/codon.git synced 2025-06-03 15:03:52 +08:00
codon/stdlib/internal/sort.codon

60 lines
1.6 KiB
Python
Raw Normal View History

2022-01-24 08:17:01 +01:00
# (c) 2022 Exaloop Inc. All rights reserved.
2021-09-27 14:02:44 -04: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-26 17:30:18 +01:00
from algorithms.timsort import tim_sort_inplace
2021-09-27 14:02:44 -04:00
2022-01-24 08:17:01 +01:00
def sorted(
2021-09-27 14:02:44 -04:00
v: Generator[T],
2022-01-24 08:17:01 +01:00
key=Optional[int](),
2021-09-27 14:02:44 -04:00
algorithm: Optional[str] = None,
reverse: bool = False,
2022-01-24 08:17:01 +01:00
T: type,
) -> List[T]:
2021-09-27 14:02:44 -04: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 08:17:01 +01:00
def _sort_list(
self: List[T], key: Callable[[T], S], algorithm: str, T: type, S: type
2022-02-16 16:51:16 +01:00
):
2022-01-26 17:30:18 +01:00
if algorithm == "tim":
tim_sort_inplace(self, key)
elif algorithm == "pdq":
2021-09-27 14:02:44 -04:00
pdq_sort_inplace(self, key)
2022-01-24 08:17:01 +01:00
elif algorithm == "insertion":
2021-09-27 14:02:44 -04:00
insertion_sort_inplace(self, key)
2022-01-24 08:17:01 +01:00
elif algorithm == "heap":
2021-09-27 14:02:44 -04:00
heap_sort_inplace(self, key)
2022-01-24 08:17:01 +01:00
elif algorithm == "quick":
2021-09-27 14:02:44 -04:00
qsort_inplace(self, key)
else:
2022-02-16 16:51:16 +01:00
raise ValueError(f"Algorithm '{algorithm}' does not exist")
2021-09-27 14:02:44 -04:00
2022-01-24 08:17:01 +01:00
2021-09-27 14:02:44 -04:00
@extend
class List:
def sort(
self,
2022-01-24 08:17:01 +01:00
key=Optional[int](),
2021-09-27 14:02:44 -04:00
algorithm: Optional[str] = None,
2022-01-24 08:17:01 +01:00
reverse: bool = False,
2022-02-16 16:51:16 +01:00
):
algorithm: str = algorithm if algorithm is not None else "tim"
2021-09-27 14:02:44 -04:00
if isinstance(key, Optional):
2022-02-16 16:51:16 +01:00
_sort_list(self, lambda x: x, algorithm)
2021-09-27 14:02:44 -04:00
else:
2022-02-16 16:51:16 +01:00
_sort_list(self, key, algorithm)
2021-09-27 14:02:44 -04:00
if reverse:
self.reverse()