N ERRORN = 1: A1N = 2: merge A1 & A2;
{
N > 2:
merge A1 & A2 -> A12;
merge A12 & A3 -> A13;
...
merge A1(N-1) & AN.
}
recursive way is simple for thinking. but this will loop for N-1 times, and the remove operations will cost a lot of waste.
another thinking about {} part:
while (N>1):
getMaxTail(A1...AN)
A[index--] = Max
if AX.len == 0:
N - 1
1. while loop break condition
2. tail condtion (plus one sorted array?)
3. N is large number
http://www.shahuwang.com/?p=327
[code="python"]'''
MergeSortedArrays.py
Write a code to merge N sorted array
'''
def mergeTwoSortedArrays(a, b):
print 'start mergeTwoSortedArrays'
aIndex = a.__len__() - 1
bIndex = b.__len__() - 1
index = aIndex + bIndex + 2
r = [0]*index
index-=1
while aIndex >= 0 and bIndex >=0:
if a[aIndex] > b[bIndex]:
r[index] = a[aIndex]
index-=1
aIndex-=1
else:
r[index] = b[bIndex]
index-=1
bIndex-=1
while aIndex >= 0:
r[index] = a[aIndex]
index -= 1
aIndex -= 1
while bIndex >= 0:
r[index] = b[bIndex]
index -= 1
bIndex -= 1
print r
if __name__ == '__main__':
print 'hello MergeSortedArrays'
a = [1,2,3]
print a
b = [1, 4, 6]
print b
mergeTwoSortedArrays(a, b)