Skip to content

Commit 0257933

Browse files
author
Joseph Luce
authored
Update 912_sort_an_array.md
1 parent 691a608 commit 0257933

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

leetcode/medium/912_sort_an_array.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,41 @@ class Solution(object):
7171
quick_sort(0, len(nums)-1)
7272
return nums
7373
```
74+
75+
## Merge Sort
76+
77+
- Runtime: O(Nlog(N))
78+
- Space: O(N)
79+
- N = Number of elements in list
80+
81+
Merge sort first breaks up the list into elements of one.
82+
Then from those small elements, merges them together by comparing each left and right list.
83+
Each left and right list that gets returned is in sorted order, so its a simple two pointer solution to merge the two lists into a larger sorted list. Return this larger sorted list up the recursion and repeat until the entire subset is sorted.
84+
85+
Merge sort is considered a stable sort.
86+
87+
```
88+
class Solution:
89+
def sortArray(self, nums: List[int]) -> List[int]:
90+
91+
def merge_sort(nums):
92+
if len(nums) <= 1:
93+
return nums
94+
mid_idx = len(nums) // 2
95+
left = merge_sort(nums[:mid_idx])
96+
right = merge_sort(nums[mid_idx:])
97+
left_idx = right_idx = 0
98+
merged = list()
99+
while left_idx < len(left) and right_idx < len(right):
100+
if left[left_idx] < right[right_idx]:
101+
merged.append(left[left_idx])
102+
left_idx += 1
103+
else:
104+
merged.append(right[right_idx])
105+
right_idx += 1
106+
merged += left[left_idx:]
107+
merged += right[right_idx:]
108+
return merged
109+
110+
return merge_sort(nums)
111+
```

0 commit comments

Comments
 (0)