diff --git a/TP9/tri-fusion/merge_sort.py b/TP9/tri-fusion/merge_sort.py index b29cf009f3586c390a66b69505348ca65ec51549..5efd147623453dc0be191a3efc47785bb9b0245c 100755 --- a/TP9/tri-fusion/merge_sort.py +++ b/TP9/tri-fusion/merge_sort.py @@ -61,7 +61,6 @@ def length(li: ApLst) -> int: else: return 1+length(li.tail()) -length(ApLst(3, ApLst(1, ApLst(4, ApLst())))) def native_to_list(li: list[T]) -> ApLst: """ @@ -143,7 +142,15 @@ def split(l: ApLst) -> tuple[ApLst, ApLst]: $$$ all(k in l for k in l3) True """ - ... + if length(l)>=2: + l1=ApLst(l.head(),split((l.tail()).tail())[0]) + l2=ApLst((l.tail()).head(),split((l.tail()).tail())[1]) + return(l1,l2) + if l.is_empty(): + return (ApLst(),ApLst()) + if length(l)==1: + return (ApLst(l.head(),ApLst()),ApLst()) + def merge(l1: ApLst, l2: ApLst, @@ -158,7 +165,21 @@ def merge(l1: ApLst, l2: ApLst, $$$ list_to_native(merge(native_to_list([1, 3, 4, 9]), native_to_list([1, 2, 5]))) [1, 1, 2, 3, 4, 5, 9] """ - ... + res=[] + while not (l1.is_empty() or l2.is_empty()): + if comp(l1.head(),l2.head())<0: + res.append(l1.head()) + l1=l1.tail() + else: + res.append(l2.head()) + l2=l2.tail() + while not l1.is_empty(): + res.append(l1.head()) + l1=l1.tail() + while not l2.is_empty(): + res.append(l2.head()) + l2=l2.tail() + return native_to_list(res) def mergesort(l: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst: