-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0912-sort-an-array.py
32 lines (30 loc) · 976 Bytes
/
0912-sort-an-array.py
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
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def merge(arr, L, M, R):
left, right = arr[L:M+1], arr[M+1:R+1]
i, j, k = L, 0, 0
while j < len(left) and k < len(right):
if left[j] <= right[k]:
arr[i] = left[j]
j += 1
else:
arr[i] = right[k]
k += 1
i += 1
while j < len(left):
nums[i] = left[j]
j += 1
i += 1
while k < len(right):
nums[i] = right[k]
k += 1
i += 1
def mergeSort(arr, l, r):
if l == r:
return arr
m = (l + r) // 2
mergeSort(arr, l, m)
mergeSort(arr, m + 1, r)
merge(arr, l, m, r)
return arr
return mergeSort(nums, 0, len(nums) - 1)