Skip to content

Commit 9e8927e

Browse files
Added one more example (#144)
* Added one more example Added one more example to explain the recursion stack of merge sort to provide in-depth knowledge of the algorithm. Also added best case, worst case, and average time complexity. * Update en/Sorting Algorithms/Merge Sort.md Co-authored-by: David Leal <halfpacho@gmail.com> Co-authored-by: David Leal <halfpacho@gmail.com>
1 parent 557eb53 commit 9e8927e

File tree

1 file changed

+30
-2
lines changed

1 file changed

+30
-2
lines changed

en/Sorting Algorithms/Merge Sort.md

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,17 @@ Given an array of n elements, write a function to sort the array
1212

1313
#### Time Complexity
1414

15-
`O(n log n)`
15+
```
16+
Best case - O(n log n)
17+
Average - O(n log n)
18+
Worst case - O(n log n)
19+
```
1620

1721
#### Space Complexity
1822

1923
`O(n)`
2024

21-
#### Example
25+
#### Example 1
2226

2327
```
2428
arr = [1, 3, 9, 5, 0, 2]
@@ -31,6 +35,30 @@ Recursively call merge sort function for both these halves which will provide so
3135
Now merge both these halves to get the sorted array [0, 1, 2, 3, 5, 9]
3236
```
3337

38+
#### Example 2
39+
40+
```
41+
arr = [1, 9, 2, 5, 7, 3, 6, 4]
42+
43+
Divide the array into two halves [1, 9, 2, 5] and [7, 3, 6, 4]
44+
45+
As you can see that the above two halves are not yet sorted, so divide both of them into two halves again.
46+
47+
This time we get four arrays as [1, 9], [2, 5], [7, 3] and [6, 4].
48+
49+
We see that the last two arrays are again not sorted, so we divide them again into two halves and we will get [7], [3], [6], and [4].
50+
51+
Since an array of a single element is sorted, we now have all the arrays sorted, now we only need to merge them appropriately.
52+
53+
First, the arrays of one element will be merged as they were divided in last, and are at top of the recursion stack, so we get [3,7] and [4,6].
54+
55+
Now the merge will occur accordingly to the recursion stack, [1, 9] and [2, 5] will be merged and will make [1, 2, 5, 9].
56+
57+
Similarly [3, 7] and [4, 6] will be merged and made [3, 4, 6, 7].
58+
59+
At the next stack level [1, 2, 5, 9] and [3, 4, 6, 7] will be merged and we will get the final sorted array as [1, 2, 3, 4, 5, 6, 7, 9].
60+
```
61+
3462
#### Code Implementation Links
3563

3664
- [Java](https://github.com/TheAlgorithms/Java/blob/master/Sorts/MergeSort.java)

0 commit comments

Comments
 (0)