Skip to main content

Merge Sort

Definition​

Merge Sort is a popular comparison-based sorting algorithm that follows the divide-and-conquer paradigm. It recursively divides the input array into smaller sub-arrays until each sub-array contains only one element, then merges those sub-arrays in a sorted manner

Practice​

mergeSort(array)
if length of array <= 1
return array
else
mid = length of array / 2
leftArray = mergeSort(first half of array)
rightArray = mergeSort(second half of array)
return merge(leftArray, rightArray)

merge(leftArray, rightArray)
result = []
while leftArray is not empty and rightArray is not empty
if first element of leftArray <= first element of rightArray
append first element of leftArray to result
remove first element from leftArray
else
append first element of rightArray to result
remove first element from rightArray
append remaining elements of leftArray to result
append remaining elements of rightArray to result
return result