如何在Python中对两个向量进行排序?

时间:2018-09-01 20:12:24

标签: python arrays python-3.x

我需要编写一个函数,该函数接收已经按升序排序的两个数组(A []​​和B []),它的函数分配一个数组C [],数组C []的大小恰好是A和B的总和,然后将C []中A []和B []的元素,因此数组C []以升序排列。尽可能高效地编写函数。不能使用Bubble方法或Insertion来连接数组和对数组C []进行排序。

示例: A [] = {1,3,6,7}和B [] = {2,4,5},新向量为C [] = {1,2,3,4,5,6,7} < / p>

我的代码不会停止运行,我在做什么错了?

def union(v1, v2):
    c = [0, 0, 0, 0, 0, 0, 0, 0]
    auxv1 = 0
    auxv2 = 0
    i = 0
    j = 0
    k = 0
    while i < len(v1)-1:
        auxv1 = v1[i]
    while j < len(v2)-1:
        auxv2 = v2[j]
    while k < len(c):
        if auxv1 < auxv2:
            c[k] = auxv1
            i += 1
            k += 1
        else:
            c[k] = auxv2
            j += 1
            k += 1
    if i == len(v1)-1 and j == len(v2)-1:
        return c

2 个答案:

答案 0 :(得分:1)

您可以仅遍历两个列表,然后将ca的元素添加到列表b中,以较小的元素为准。
一个例子如下。

c=[]
i = j = 0

while True:
    if j == len(b):
        c+=a[i:]
        break
    elif i == len(a):
        c+=b[j:]
        break
    elif a[i] < b[j]:
        c.append(a[i])
        i+=1
    else:
        c.append(b[j])
        j+=1

相对于两个列表的长度,此方法的时间复杂度为linear

答案 1 :(得分:0)

@newbie编写了一个非常清晰的算法,该算法也非常快-它进行的列表操作的数量与结果中元素的数量完全相等,即线性。

但是,通过查看一个列表中的值的运行,您可以找到一个亚线性算法,该算法应插入另一列表中的下一个值之前。

我猜想这可以在较长的列表上以较大的运行速度执行..(通常,在性能方面,您需要使用自己的数据对其进行测试)。

a = [1,3,6,7]
b = [2,4,5,9,11,12,13,14,15,16]
c = []

a1 = a2 = b1 = b2 = 0
alen = len(a)
blen = len(b)
clen = alen + blen

while a2 + b2 < clen:
    print "processed:", a2 + b2
    if b2 == blen:    # done with b..
        c += a[a1:]   # just append rest of a
        break         # and we're done
    else:
        # find indexes a1..a2 such that all items come before the next b
        next_b = b[b2]
        while a2 < alen and a[a2] < next_b:
            a2 += 1
        c += a[a1:a2]   # extend c with the chunk we've found
        a1 = a2

    if a2 == alen:    # we're done with a
        c += b[b1:]   # just append rest of b
        break         # and we're done
    else:
        next_a = a[a2]
        while b2 < blen and b[b2] < next_a:
            b2 += 1
        c += b[b1:b2]
        b1 = b2

print c