codon/stdlib/algorithms/insertionsort.codon

48 lines
1.0 KiB
Python
Raw Normal View History

2022-01-24 11:00:35 +08:00
# (c) 2022 Exaloop Inc. All rights reserved.
def _insertion_sort(
arr: Array[T], begin: int, end: int, keyf: Callable[[T], S], T: type, S: type
2022-02-16 23:51:16 +08:00
):
2021-09-28 02:02:44 +08:00
i = begin + 1
while i < end:
x = arr[i]
j = i - 1
while j >= begin and keyf(x) < keyf(arr[j]):
2022-01-24 11:00:35 +08:00
arr[j + 1] = arr[j]
2021-09-28 02:02:44 +08:00
j -= 1
2022-01-24 11:00:35 +08:00
arr[j + 1] = x
2021-09-28 02:02:44 +08:00
i += 1
2022-01-24 11:00:35 +08:00
def insertion_sort_array(
collection: Array[T], size: int, keyf: Callable[[T], S], T: type, S: type
2022-02-16 23:51:16 +08:00
):
2021-09-28 02:02:44 +08:00
"""
2022-01-24 11:00:35 +08:00
Insertion Sort
Sorts the array inplace.
2021-09-28 02:02:44 +08:00
"""
_insertion_sort(collection, 0, size, keyf)
2022-01-24 11:00:35 +08:00
def insertion_sort_inplace(
collection: List[T], keyf: Callable[[T], S], T: type, S: type
2022-02-16 23:51:16 +08:00
):
2021-09-28 02:02:44 +08:00
"""
2022-01-24 11:00:35 +08:00
Insertion Sort
Sorts the list inplace.
2021-09-28 02:02:44 +08:00
"""
insertion_sort_array(collection.arr, collection.len, keyf)
2022-01-24 11:00:35 +08:00
def insertion_sort(
collection: List[T], keyf: Callable[[T], S], T: type, S: type
) -> List[T]:
2021-09-28 02:02:44 +08:00
"""
2022-01-24 11:00:35 +08:00
Insertion Sort
Returns the sorted list.
2021-09-28 02:02:44 +08:00
"""
newlst = copy(collection)
insertion_sort_inplace(newlst, keyf)
return newlst