Skip to content

Commit

Permalink
Create 0912-sort-an-array.py
Browse files Browse the repository at this point in the history
  • Loading branch information
neetcode-gh authored Feb 18, 2023
1 parent 2a77937 commit 79d8fee
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions python/0912-sort-an-array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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)

0 comments on commit 79d8fee

Please sign in to comment.