Skip to content
Snippets Groups Projects
Commit 8be4c6b8 authored by Belkacemi Melissa's avatar Belkacemi Melissa
Browse files

merge et mergesort

parent 5ded8920
No related branches found
No related tags found
No related merge requests found
...@@ -166,15 +166,18 @@ def merge(l1: ApLst, l2: ApLst, ...@@ -166,15 +166,18 @@ def merge(l1: ApLst, l2: ApLst,
$$$ list_to_native(merge(native_to_list([1, 3, 4, 9]), native_to_list([1, 2, 5]))) $$$ list_to_native(merge(native_to_list([1, 3, 4, 9]), native_to_list([1, 2, 5])))
[1, 1, 2, 3, 4, 5, 9] [1, 1, 2, 3, 4, 5, 9]
""" """
if not (l1.is_empty() or l2.is_empty()): if (not l1.is_empty()) and (not l2.is_empty()):
if comp(l1.head(),l2.head())<0: h1,h2= l1.head(),l2.head()
return ApLst(l1.head(),merge(l1.tail(),l2)) if comp(h1,h2)<=0:
res= ApLst(h1,merge(l1.tail(),l2))
else: else:
return ApLst(l2.head(),merge(l1,l2.tail())) res= ApLst(h2,merge(l1,l2.tail()))
elif not l1.is_empty(): else:
return l1 if l1.is_empty():
elif not l2.is_empty(): res= l2
return l2 else:
res= l1
return res
def mergesort(l: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst: def mergesort(l: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst:
""" """
...@@ -194,7 +197,12 @@ def mergesort(l: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst: ...@@ -194,7 +197,12 @@ def mergesort(l: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst:
$$$ is_sorted(l1) $$$ is_sorted(l1)
True True
""" """
... l1,l2=split(l)
if length(l)<=2:
return merge(l1,l2)
else:
return merge(mergesort(l1),mergesort(l2))
if (__name__ == '__main__'): if (__name__ == '__main__'):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment