Update adaptive_merge_sort.py

This commit is contained in:
ANANT JAIN 2024-10-17 01:34:31 +05:30 committed by GitHub
parent eb3284d6f0
commit c8397d47cf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -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. Sorts a list using the Adaptive Merge Sort algorithm.
@ -17,6 +17,7 @@ def adaptive_merge_sort(sequence: list) -> list:
""" """
if len(sequence) < 2: if len(sequence) < 2:
return sequence return sequence
aux = sequence[:] aux = sequence[:]
print(f"Initial sequence: {sequence}") print(f"Initial sequence: {sequence}")
adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1) 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: if high <= low:
return return
mid = (low + high) // 2 mid = (low + high) // 2
print(f"Sorting: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]") 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, low, mid)
adaptive_merge_sort_helper(aux, array, mid + 1, high) adaptive_merge_sort_helper(aux, array, mid + 1, high)
if array[mid] <= array[mid + 1]: if array[mid] <= array[mid + 1]:
print(f"Skipping merge as 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 return
merge(array, aux, low, mid, high) 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] After merge: [1, 2, 3, 4]
""" """
print(f"Merging: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]") print(f"Merging: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]")
i, j = low, mid + 1 i, j = low, mid + 1
for k in range(low, high + 1): for k in range(low, high + 1):
if i > mid: if i > mid:
@ -68,13 +74,19 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
elif j > high: elif j > high:
aux[k] = array[i] aux[k] = array[i]
i += 1 i += 1
elif array[j] < array[i]: elif array[i] <= array[j]: # Keep stable by using <=
aux[k] = array[j]
j += 1
else:
aux[k] = array[i] aux[k] = array[i]
i += 1 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): for k in range(low, high + 1):
array[k] = aux[k] 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]))