From c8397d47cf161104a7463d563a69a81a2b87b1a8 Mon Sep 17 00:00:00 2001 From: ANANT JAIN <139585700+anant-jain01@users.noreply.github.com> Date: Thu, 17 Oct 2024 01:34:31 +0530 Subject: [PATCH] Update adaptive_merge_sort.py --- sorts/adaptive_merge_sort.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/sorts/adaptive_merge_sort.py b/sorts/adaptive_merge_sort.py index 3a29d110f..4ce64f370 100644 --- a/sorts/adaptive_merge_sort.py +++ b/sorts/adaptive_merge_sort.py @@ -1,4 +1,4 @@ -def adaptive_merge_sort(sequence: list) -> list: + def adaptive_merge_sort(sequence: list) -> list: """ Sorts a list using the Adaptive Merge Sort algorithm. @@ -17,6 +17,7 @@ def adaptive_merge_sort(sequence: list) -> list: """ if len(sequence) < 2: return sequence + aux = sequence[:] print(f"Initial sequence: {sequence}") adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1) @@ -40,14 +41,18 @@ def adaptive_merge_sort_helper(array: list, aux: list, low: int, high: int) -> N """ if high <= low: return + mid = (low + high) // 2 print(f"Sorting: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]") + adaptive_merge_sort_helper(aux, array, low, mid) adaptive_merge_sort_helper(aux, array, mid + 1, high) + if array[mid] <= array[mid + 1]: print(f"Skipping merge as array[{mid}] <= array[{mid + 1}]") - array[low : high + 1] = aux[low : high + 1] + array[low:high + 1] = aux[low:high + 1] return + merge(array, aux, low, mid, high) @@ -60,6 +65,7 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None: After merge: [1, 2, 3, 4] """ print(f"Merging: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]") + i, j = low, mid + 1 for k in range(low, high + 1): if i > mid: @@ -68,13 +74,19 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None: elif j > high: aux[k] = array[i] i += 1 - elif array[j] < array[i]: - aux[k] = array[j] - j += 1 - else: + elif array[i] <= array[j]: # Keep stable by using <= aux[k] = array[i] i += 1 - # Ensure we correctly copy back to the main array + else: + aux[k] = array[j] + j += 1 + for k in range(low, high + 1): array[k] = aux[k] - print(f"After merge: {aux[low:high + 1]}") + + print(f"After merge: {array[low:high + 1]}") + + +# Example usage +if __name__ == "__main__": + print(adaptive_merge_sort([4, 3, 1, 2]))