-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path912_Sort_an_Array.py
More file actions
30 lines (24 loc) · 851 Bytes
/
Copy path912_Sort_an_Array.py
File metadata and controls
30 lines (24 loc) · 851 Bytes
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
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
return self.mergeSort(nums)
def mergeSort(self, arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
leftPortion = self.mergeSort(arr[0:mid])
rightPortion = self.mergeSort(arr[mid:])
# merge two sorted portion
i = 0
j = 0
sortedArr = []
while(i < len(leftPortion) and j < len(rightPortion)):
if leftPortion[i] < rightPortion[j]:
sortedArr.append(leftPortion[i])
i += 1
else:
sortedArr.append(rightPortion[j])
j += 1
# appending leftover elements
sortedArr.extend(leftPortion[i:])
sortedArr.extend(rightPortion[j:])
return sortedArr