Detailed Merge Sort Algorithm
Detailed Merge Sort Algorithm
Overview
Merge Sort is a classic divide-and-conquer algorithm used for sorting an array or list. It
recursively divides the input array into two halves until each sub-array has only one element, and
then merges these sub-arrays back together in a sorted manner.
Key Concepts
1 Divide-and-Conquer:
◦ Merge Sort preserves the relative order of equal elements, making it a stable sort.
3 Time Complexity:
◦ Merge Sort has a consistent time complexity of O ( n log n ) O(nlogn) for all
cases (best, average, and worst).
4 Space Complexity:
◦ It requires additional space proportional to the size of the input array, with O ( n )
O(n) auxiliary space.
Steps in Merge Sort
1 Divide:
◦ If the array has more than one element, split it into two sub-arrays: the left half and the
right half.
◦ This division is continued recursively until each sub-array contains a single element.
2 Conquer:
◦ Recursively sort the left and right halves. Since an array with one element is already
sorted, this step naturally completes once the division step reaches individual
elements.
3 Combine:
• Initialization:
◦ Use two pointers to track positions in the left and right sub-arrays.
• Comparison:
◦ When one sub-array is exhausted, append the remaining elements of the other sub-
array to the result array.
Example of Merge Sort
1 Divide:
1. Algorithm Type
• Merge Sort: Consistent O ( n log n ) O(nlogn) for best, average, and worst cases.
• Heap Sort: O ( n log n ) O(nlogn) for best and average cases, and worst case O ( n
log n ) O(nlogn).
4. Space Complexity
• Merge Sort: Well-suited for linked lists as merging can be done in-place with O ( 1 )
O(1) space.
• Heap Sort: Not suitable for linked lists; operations are efficient on arrays.
7. Use Cases
• Merge Sort: Preferred when stable sort is required or for sorting linked lists.
• Heap Sort: Used when in-place sorting is necessary and additional space is a constraint.
8. Merging vs. Heapifying
• Merge Sort is efficient for stable sorting, especially with linked lists or when predictable
performance is required.
• Heap Sort is useful for memory-constrained environments requiring in-place sorting but may
not be stable.
Both sorting algorithms have their strengths and are suited for different scenarios, providing
flexibility and efficiency depending on the application requirements.