algorithm_merge
来源:互联网 发布:服务器php升级 编辑:程序博客网 时间:2024/06/17 02:17
def merge(A,p,q,r): s=p t=q+1 k=p #s,t are the subarray index,k is B[] index B=[] while s<=q and t<=r: if A[s]<=A[t]: B.append(A[s]) s=s+1 else: B.append(A[t]) t=t+1 print s,t, print B if s==q+1: B.extend(A[t:r+1]) else: B.extend(A[s:q+1]) #when one subarray is finished A[p:r+1]=B[p:r+1] #copy B to A print A ''' M=[1,2,3,4,5,8,10,12,2,4,5,7,9,11] merge(M,0,7,len(M)-1) 1,2,3,4,5,8,10,12 2,4,5,7,9,11 '''
1.同一数组内的两段已排序的子序列合并,主要是为以后bottomup算法调用考虑。
2.python列表的append和extend方法用在此处有如神助,不知道它们的时间消耗,应该和比较 赋值之类一样的吧。