-
Notifications
You must be signed in to change notification settings - Fork 0
/
sequential-merge.py
61 lines (49 loc) · 1.45 KB
/
sequential-merge.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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Implementation of Sequential Merge algorithm
given in Problem 1.3 on page 33 of the book Algorithms Illuminated
by Tim Roughgarden
Author: Ibad Desmukh
Date: 2024-09-30
Copyright (c) 2024 Ibad Desmukh. All rights reserved
"""
"""
k: number of arrays
n: number of elements in each array
"""
def merge(A, B):
# Total length of both arrays, or the length of result array
n = len(A) + len(B)
# Initialise empty result array
result = [0] * n
i = 0 # Index to keep track of A
j = 0 # Index to keep track of B
k = 0 # Index to keep track of result
# While both A and B have not been exhausted
while i < len(A) and j < len(B):
# Add elements based on comparison
if A[i] < B[j]:
result[k] = A[i]
i += 1
else:
result[k] = B[j]
j += 1
# Increment k to run the while loop
k += 1
# If i/j are still less than the lengths of A/B, keep running to add remaining elements to result
while i < len(A):
result[k] = A[i]
i += 1
k += 1
while j < len(B):
result[k] = B[j]
j += 1
k += 1
return result
# Function to recursively run the merge function across arrays
def sequential_merge(arrays):
result = arrays[0]
for i in range(1, len(arrays)):
result = merge(result, arrays[i])
return result
arrays = [[1, 4, 7], [2, 5, 8], [3, 6, 9], [0, 10, 11]]
print(sequential_merge(arrays))