Problem A
Uppgift
Swipe to start coding
The task is to merge given sorted arrays arr1
and arr2
. Do not use ready code from Merge Sort Algorithm.
How to merge: you have two sorted arrays arr1
and arr2
, let’s set pointers p1
and p2
at the beginning of each of them (p1=0
, p2=0
).
Compare current values: if arr1[p1] < arr2[p2]
, then put arr1[p1]
to temp
and increase p1
by 1. Else do the same for p2
.
If one of the pointers reaches max possible value (out of bounds), you can not check, and store all rest elements from another array.
Do the following until p1 < len(arr1) or p2 < len(arr2)
.
Lösning
99
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
def merge(arr1, arr2):
i, j = 0, 0
n1, n2 = len(arr1), len(arr2)
temp = []
while i<n1 or j<n2:
if i >= n1:
temp.append(arr2[j])
j+=1
elif j>=n2:
temp.append(arr1[i])
i+=1
else:
if arr1[i] < arr2[j]:
temp.append(arr1[i])
i+=1
else:
temp.append(arr2[j])
j+=1
return temp
arr1 = [-9.1, -7.9, -6.4, -1.7, -1.4, -0.8, 2.0, 4.7, 7.4, 8.3]
arr2 = [-6.1, -6.1, -4.1, -3.2, 2.0, 4.1, 5.3, 6.5, 8.0, 8.5]
ans = merge(arr1, arr2)
print(ans)
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 3. Kapitel 1
9
1
2
3
4
5
6
7
def merge(arr1, arr2):
# Your code
arr1 = [-9.1, -7.9, -6.4, -1.7, -1.4, -0.8, 2.0, 4.7, 7.4, 8.3]
arr2 = [-6.1, -6.1, -4.1, -3.2, 2.0, 4.1, 5.3, 6.5, 8.0, 8.5]
# Print the answer
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal