mirror of
https://github.com/exaloop/codon.git
synced 2025-06-03 15:03:52 +08:00
stdlib/algorithms/insertionsort.codon
This commit is contained in:
parent
ea2e9a382d
commit
de18d69e22
@ -1,32 +1,46 @@
|
|||||||
def _insertion_sort[S,T](arr: Array[T], begin: int, end: int, keyf: Callable[[T], S]):
|
# (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
|
||||||
|
) -> void:
|
||||||
i = begin + 1
|
i = begin + 1
|
||||||
while i < end:
|
while i < end:
|
||||||
x = arr[i]
|
x = arr[i]
|
||||||
j = i - 1
|
j = i - 1
|
||||||
while j >= begin and keyf(x) < keyf(arr[j]):
|
while j >= begin and keyf(x) < keyf(arr[j]):
|
||||||
arr[j+1] = arr[j]
|
arr[j + 1] = arr[j]
|
||||||
j -= 1
|
j -= 1
|
||||||
arr[j+1] = x
|
arr[j + 1] = x
|
||||||
i += 1
|
i += 1
|
||||||
|
|
||||||
def insertion_sort_array[S,T](collection: Array[T], size: int, keyf: Callable[[T], S]):
|
|
||||||
|
def insertion_sort_array(
|
||||||
|
collection: Array[T], size: int, keyf: Callable[[T], S], T: type, S: type
|
||||||
|
) -> void:
|
||||||
"""
|
"""
|
||||||
Insertion Sort
|
Insertion Sort
|
||||||
Sorts the array inplace.
|
Sorts the array inplace.
|
||||||
"""
|
"""
|
||||||
_insertion_sort(collection, 0, size, keyf)
|
_insertion_sort(collection, 0, size, keyf)
|
||||||
|
|
||||||
def insertion_sort_inplace[S,T](collection: List[T], keyf: Callable[[T], S]):
|
|
||||||
|
def insertion_sort_inplace(
|
||||||
|
collection: List[T], keyf: Callable[[T], S], T: type, S: type
|
||||||
|
) -> void:
|
||||||
"""
|
"""
|
||||||
Insertion Sort
|
Insertion Sort
|
||||||
Sorts the list inplace.
|
Sorts the list inplace.
|
||||||
"""
|
"""
|
||||||
insertion_sort_array(collection.arr, collection.len, keyf)
|
insertion_sort_array(collection.arr, collection.len, keyf)
|
||||||
|
|
||||||
def insertion_sort[S,T](collection: List[T], keyf: Callable[[T], S]) -> List[T]:
|
|
||||||
|
def insertion_sort(
|
||||||
|
collection: List[T], keyf: Callable[[T], S], T: type, S: type
|
||||||
|
) -> List[T]:
|
||||||
"""
|
"""
|
||||||
Insertion Sort
|
Insertion Sort
|
||||||
Returns the sorted list.
|
Returns the sorted list.
|
||||||
"""
|
"""
|
||||||
newlst = copy(collection)
|
newlst = copy(collection)
|
||||||
insertion_sort_inplace(newlst, keyf)
|
insertion_sort_inplace(newlst, keyf)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user