Definition
Merge Sort is a divide-and-conquer sorting algorithm that recursively splits an array into halves until each subarray contains a single element, then merges them back together in sorted order. The key operation is the merge step, which combines two sorted subarrays into a single sorted array by comparing elements from each subarray and selecting the smaller one at each step.
Constraints
- Requires additional O(n) space for the merging process
- Slower than Quick Sort for small datasets due to recursion overhead
- Excellent for linked lists as it doesn't require random access
- Stable sort (maintains relative order of equal elements)
Step-by-step explanation
Arguments:
- Array to be sorted -
array
- Left index of subarray -
left
- Right index of subarray -
right
- Temporary array for merging -
tempArray
- Left subarray (sorted) -
leftArray
- Right subarray (sorted) -
rightArray
Explanation:
- Divide the unsorted array into two halves at the middle index
- Recursively sort the left half
array[left..mid]
- Recursively sort the right half
array[mid+1..right]
- Merge the two sorted halves back together:
- Compare elements from both halves one by one
- Always take the smaller element and place it in the merged array
- Continue until all elements from both halves are merged
- Repeat until the entire array is sorted
Returns:
Returns nothing (sorts array
in-place in most implementations)
Some implementations may return a new sorted array while leaving the original unchanged
No explicit return value (void function in most in-place implementations)