You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Function to merge two sorted sub-arraysdefmerge(arr: list[int], p: int, q: int, r: int):
left: list[int] =arr[p:q+1] # arr[p..q]right: list[int] =arr[q+1:r+1] # arr[q+1..r]i: int=0# Pointer (index) for left sub-arrayj: int=0# Pointer for right sub-arrayk: int=p# Pointer for the original array# k is the index that tracks the position in the original array (arr)# where the next element from the sorted sub-arrays should be placed.# The "original array (arr)" refers to the full array, but during the# recursive steps of merge sort, we treat portions of it as sub-arrays# using the indices p, q, and r.# We should not set k = 0 because that would incorrectly place the merged# elements at the start of the array, overwriting previous sections and# breaking the sort.# Merge the two sub-arrays back into arr[p..r]whilei<len(left) andj<len(right):
ifleft[i] <right[j]:
arr[k] =left[i]
i+=1else:
arr[k] =right[j]
j+=1k+=1# Copy any remaining elements of left[] if anywhilei<len(left):
arr[k] =left[i]
i+=1k+=1# Copy any remaining elements of right[] if anywhilej<len(right):
arr[k] =right[j]
j+=1k+=1# Recursive merge_sort functiondefmerge_sort(arr: list[int], p: int, r: int) ->None:
ifp<r:
q: int= (p+r) //2# Find the midpoint, taking the floor valuemerge_sort(arr, p, q) # Sort the first halfmerge_sort(arr, q+1, r) # Sort the second halfmerge(arr, p, q, r) # Merge the sorted halvesarr: list[int] = [2, 1, 6, 3, 4]
merge_sort(arr, 0, len(arr) -1)
print(arr) # [1, 2, 3, 4, 6]
Visualize:
The text was updated successfully, but these errors were encountered: