codon/stdlib/internal/sort.codon

57 lines
1.5 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-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
) -> void:
if 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:
raise ValueError("Algorithm '" + algorithm + "' does not exist")
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,
) -> void:
alg = ~algorithm if algorithm else "pdq"
2021-09-28 02:02:44 +08:00
if isinstance(key, Optional):
_sort_list(self, lambda x: x, alg)
else:
_sort_list(self, key, alg)
if reverse:
self.reverse()