diff --git a/Tp09/merge_sort.py b/Tp09/merge_sort.py index a78637a74dece3234ee2383bab791e5fefe96199..5d4d79d6bc50989b31d455964bd863de5932bf32 100755 --- a/Tp09/merge_sort.py +++ b/Tp09/merge_sort.py @@ -161,20 +161,27 @@ def split(l: ApLst) -> tuple[ApLst, ApLst]: $$$ all(k in l for k in l3) True """ - l1 = ApLst() - l2 = ApLst() - compteur = 0 - while not l.is_empty(): - if compteur % 2 == 0: - l1 = ApLst(l.head(), l1) +# l1 = ApLst() +# l2 = ApLst() +# compteur = 0 +# while not l.is_empty(): +# if compteur % 2 == 0: +# l1 = ApLst(l.head(), l1) +# else: +# l2 = ApLst(l.head(), l2) +# l = l.tail() +# compteur += 1 +# return (l1, l2) + if not l.is_empty(): + h1 = l.head() + if not l.tail().is_empty(): + h2 = l.tail().head() + r1, r2 = split(l.tail().tail()) + return ApLst(h1, r1), ApLst(h2, r2) else: - l2 = ApLst(l.head(), l2) - l = l.tail() - compteur += 1 - return (l1, l2) - - - + return ApLst(h1,ApLst()),ApLst() + else: + return ApLst(), ApLst() def merge(l1: ApLst, l2: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst: @@ -188,7 +195,43 @@ 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] """ - ... + if (not l1.is_empty()) and (not l2.is_empty()): + h1, h2 = l1.head(), l2.head() + if comp(h1, h2) <= 0: + res = ApLst(h1, merge(l1.tail(), l2)) + else: + res = ApLst(h2, merge(l1, l2.tail())) + else: + if l1.is_empty(): + res = l2 + else: + res = l1 + return res + +# res = [] +# if l1.is_empty() and l2.is_empty(): +# return res +# elif l1.is_empty() and not l2.is_empty(): +# res.append(l2.tail()) +# elif not l1.is_empty() and l2.is_empty(): +# res.append(l1.tail()) +# else: +# l1 = l1.head() +# l2 = l2.head() +# if compare(l1, l2) < 0: +# res.append(l1) +# l1 = l1.tail() +# merge(l1, l2) +# elif compare(l1, l2) > 0: +# res.append(l2) +# l2 = l2.tail() +# merge(l1, l2) +# else: +# res.append(l1) +# res.append(l2) +# l1 = l1.tail() +# l2 = l2.tail() +# merge(l1, l2) def mergesort(l: ApLst, comp: Callable[[T, T], int]=compare) -> ApLst: