FUNCTION mergeSort(arr, left, right)
IF left < right THEN
mid = (left + right) / 2 // Calculate the mid index
// Recursively sort the left half
mergeSort(arr, left, mid)
// Recursively sort the right half
mergeSort(arr, mid + 1, right)
// Merge the sorted halves
merge(arr, left, mid, right)
FUNCTION merge(arr, left, mid, right)
n1 = mid - left + 1 // Size of the left subarray
n2 = right - mid // Size of the right subarray
// Create temporary arrays
DECLARE leftArray[n1]
DECLARE rightArray[n2]
// Copy data to leftArray
FOR i FROM 0 TO n1 - 1 DO
leftArray[i] = arr[left + i]
// Copy data to rightArray
FOR j FROM 0 TO n2 - 1 DO
rightArray[j] = arr[mid + 1 + j]
i = 0 // Initial index for leftArray
j = 0 // Initial index for rightArray
k = left // Initial index for merged array
// Merge the temporary arrays back into arr
WHILE i < n1 AND j < n2 DO
IF leftArray[i] <= rightArray[j] THEN
arr[k] = leftArray[i] // Add the smaller element to arr
i=i+1
ELSE
arr[k] = rightArray[j] // Add the smaller element to arr
j=j+1
k=k+1
// Copy remaining elements of leftArray (if any)
WHILE i < n1 DO
arr[k] = leftArray[i]
i=i+1
k=k+1
// Copy remaining elements of rightArray (if any)
WHILE j < n2 DO
arr[k] = rightArray[j]
j=j+1
k=k+1