-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.py
More file actions
46 lines (34 loc) · 1.12 KB
/
merge_sort.py
File metadata and controls
46 lines (34 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
Merge sort is a divide and conquer algorithm that divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves.
"""
class Solution:
def merge_sort(self, nums):
n = len(nums)
if n <= 1:
return nums
mid = n // 2
left_half = self.merge_sort(nums[:mid])
right_half = self.merge_sort(nums[mid:])
return self._merge(left_half, right_half)
def _merge(self, left, right):
i, j = 0, 0
result = []
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# Time Complexity: O(n log n)
# Space Complexity: O(n)
if __name__ == "__main__":
solution = Solution()
nums = [38, 27, 43, 3, 9, 82, 10]
result = solution.merge_sort(nums)
assert result == [3, 9, 10, 27, 38, 43, 82]
print(result)
print("Test Case Passed!")