Skip to content

Commit e5b6ef2

Browse files
committed
12.4
1 parent 357b654 commit e5b6ef2

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

464.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution:
2+
"""
3+
@param A: an integer array
4+
@return: nothing
5+
"""
6+
def sortIntegers2(self, A):
7+
# write your code here
8+
if len(A) <= 0:
9+
return []
10+
return Solution.subsort(1, A)
11+
12+
def subsort(self, arr):
13+
if len(arr) <= 1:
14+
return arr
15+
if len(arr) == 2:
16+
if(arr[0] > arr[1]):
17+
return [arr[1], arr[0]]
18+
else:
19+
return arr
20+
else:
21+
size = len(arr)
22+
return Solution.merge(1, Solution.subsort(1, arr[:size//2]), Solution.subsort(1, arr[size//2:]))
23+
24+
def merge(self, arr1, arr2):
25+
res = []
26+
if len(arr1) == 0:
27+
return arr2
28+
if len(arr2) == 0:
29+
return arr1
30+
i, j = 0, 0
31+
while i < len(arr1) and j < len(arr2):
32+
if arr1[i] < arr2[j]:
33+
res.append(arr1[i])
34+
i += 1
35+
else :
36+
res.append(arr2[j])
37+
j += 1
38+
if i == len(arr1):
39+
while j < len(arr2):
40+
res.append(arr2[j])
41+
j += 1
42+
if j == len(arr2):
43+
while i < len(arr1):
44+
res.append(arr1[i])
45+
i += 1
46+
return res
47+
48+
print(Solution.sortIntegers2(1, [3, 2, 1, 4, 5, 7, 6, 8]))
49+
print(Solution.sortIntegers2(1, []))
50+
print(Solution.sortIntegers2(1, [3, 2, 1, 4, 5, 7, 6]))
51+
print(Solution.sortIntegers2(1, [3,2,1,4,5]))

0 commit comments

Comments
 (0)