Write a code to merge N sorted array

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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值