Skip to content

Commit 25b5f5d

Browse files
committed
912. Sort an Array.
- Language: Python. - Time complexity: O(n log n). - Space complexity: O(3n + log n). O(log n) - for call stack. - Method: Recursive Merge Sort With Slices.
1 parent 254dc5d commit 25b5f5d

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

python_solutions/lc_912_sort_an_array/__init__.py

Whitespace-only changes.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def sortArray(self, nums: list[int]) -> list[int]:
3+
# Time complexity: O(n log n). Space complexity: O(3n).
4+
# Method: Recursive Merge Sort With Slices
5+
return self._merge_sort(nums)
6+
7+
def _merge_sort(self, nums: list[int]):
8+
if len(nums) < 2:
9+
return nums
10+
mid = len(nums) // 2
11+
ar1, ar2 = nums[:mid], nums[mid:]
12+
return self._merge_two_arrays(self._merge_sort(ar1), self._merge_sort(ar2))
13+
14+
def _merge_two_arrays(self, ar1: list[int], ar2: list[int]) -> list[int]:
15+
len1, len2 = len(ar1), len(ar2)
16+
i, j = 0, 0
17+
ans = [0] * (len1 + len2)
18+
while i < len1 or j < len2:
19+
if j == len2 or i < len1 and ar1[i] < ar2[j]:
20+
ans[i + j] = ar1[i]
21+
i += 1
22+
else:
23+
ans[i + j] = ar2[j]
24+
j += 1
25+
return ans
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import pytest
2+
3+
from lc_912_sort_an_array.lc_912_sort_an_array import Solution
4+
5+
test_cases = (
6+
# preset cases
7+
([5, 2, 3, 1], [1, 2, 3, 5]),
8+
([5, 1, 1, 2, 0, 0], [0, 0, 1, 1, 2, 5]),
9+
# common cases
10+
([-5, -1, 0, -1, 4, -12, 4, -1], [-12, -5, -1, -1, -1, 0, 4, 4]),
11+
([-12, -5, -1, -1, -1, 0, 4, 4], [-12, -5, -1, -1, -1, 0, 4, 4]),
12+
([4, 4, 0, -1, -1, -1, -5, -12], [-12, -5, -1, -1, -1, 0, 4, 4]),
13+
([-1, -5, -1, 0, -1, 4, -12, 4, -1], [-12, -5, -1, -1, -1, -1, 0, 4, 4]),
14+
# corner cases
15+
([-1, -1, -1], [-1, -1, -1]),
16+
([], []),
17+
([0], [0]),
18+
([1, -1], [-1, 1]),
19+
)
20+
21+
22+
@pytest.mark.parametrize(("nums", "ans"), test_cases)
23+
def test_success_v0(nums: list[int], ans: list[int], solution: Solution):
24+
assert solution.sortArray(nums) == ans
25+
26+
27+
@pytest.fixture
28+
def solution() -> Solution:
29+
return Solution()

0 commit comments

Comments
 (0)