Skip to content

Commit 261376d

Browse files
committed
912. Sort an Array.
- Language: Python. - Time complexity: O(n log n). - Space complexity: O(2n + log n), O(log n) - for call stack. - Method: Recursive Merge Sort With Single Buffer.
1 parent 25b5f5d commit 261376d

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

python_solutions/lc_912_sort_an_array/lc_912_sort_an_array.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,40 @@ def _merge_two_arrays(self, ar1: list[int], ar2: list[int]) -> list[int]:
2323
ans[i + j] = ar2[j]
2424
j += 1
2525
return ans
26+
27+
def sortArrayV1(self, nums: list[int]) -> list[int]:
28+
# Time complexity: O(n log n). Space complexity: O(2n).
29+
# Method: Recursive Merge Sort With Single Buffer.
30+
buffer = [0] * len(nums)
31+
self._merge_sort_v1(nums, buffer, 0, len(nums) - 1)
32+
return nums
33+
34+
def _merge_sort_v1(self, nums: list[int], buffer: list[int], left: int, right: int):
35+
len = right - left + 1
36+
if len < 2:
37+
return nums
38+
mid = (right + left) // 2
39+
self._merge_sort_v1(nums, buffer, left, mid)
40+
self._merge_sort_v1(nums, buffer, mid + 1, right)
41+
self._merge_two_arrays_v1(nums, buffer, left, mid, mid + 1, right)
42+
43+
def _merge_two_arrays_v1(
44+
self,
45+
nums: list[int],
46+
buffer: list[int],
47+
left1: int,
48+
right1: int,
49+
left2: int,
50+
right2: int,
51+
) -> None:
52+
i, j, n = left1, left2, left1
53+
while i <= right1 or j <= right2:
54+
if j > right2 or i <= right1 and nums[i] < nums[j]:
55+
buffer[n] = nums[i]
56+
i += 1
57+
else:
58+
buffer[n] = nums[j]
59+
j += 1
60+
n += 1
61+
for n in range(left1, right2 + 1):
62+
nums[n] = buffer[n]

python_solutions/lc_912_sort_an_array/test_lc_912_sort_an_array.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ def test_success_v0(nums: list[int], ans: list[int], solution: Solution):
2424
assert solution.sortArray(nums) == ans
2525

2626

27+
@pytest.mark.parametrize(("nums", "ans"), test_cases)
28+
def test_success_v1(nums: list[int], ans: list[int], solution: Solution):
29+
assert solution.sortArrayV1(nums) == ans
30+
31+
2732
@pytest.fixture
2833
def solution() -> Solution:
2934
return Solution()

0 commit comments

Comments
 (0)