Merge Sort
- A Divide and Conquer AlgorithmMerge Sort
is an efficient, stable, and comparison-based sorting algorithm that follows the divide and conquer paradigm. It is particularly useful for large datasets as it has a worst-case time complexity of O(n log n).
Merge Sort follows three main steps:
Consider the array: [8, 3, 5, 4, 2, 7, 6, 1]
Divide
[8, 3, 5, 4] | [2, 7, 6, 1]
Splitting further: [8, 3] | [5, 4] and [2, 7] | [6, 1]
Each sub-array with one element is considered sorted: [8] [3] [5] [4] [2] [7] [6] [1]
Merge each pair of sub-arrays in sorted order:
[8]
and [3]
→ [3, 8]
[5]
and [4]
→ [4, 5]
[2]
and [7]
→ [2, 7]
[6]
and [1]
→ [1, 6]
Now merge these intermediate arrays:
[3, 8]
and [4, 5]
→ [3, 4, 5, 8]
[2, 7]
and [1, 6]
→ [1, 2, 6, 7]
Finally, merge [3, 4, 5, 8]
and [1, 2, 6, 7]
→ [1, 2, 3, 4, 5, 6, 7, 8]
O(n log n).
https://drawtocode.vercel.app/problems/merge-sort
Loading component...
Loading component...