def merge_sort(array,p,q,r): n1 = q-p n2 = r-q+1 l = np.zeros(n1+1) r = np.zeros(n2+1) for i in range(0,n1): l[i] = array[p+i] for j in range(0,n2): r[j] = array[q+j] #return r l[n1] = float("inf") r[n2] = float("inf") #return l[0] l = sorted(l) r = sorted(r) #return r i = 0 j = 0 for k in range(p,r): if l[i] <= r[j]: array[k] = l[i] i = i+1 else: array[k] = r[j] j = j+1 return array 上面的代码是基于MIT的算法导论一书写的,运行后报错如下:
>>> merge_sort([4,8,12,1,7,3,9],0,3,6) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 16, in merge_sort TypeError: range() integer end argument expected, got list.