首页 > 代码库 > [算法导论]merge sort @ Python
[算法导论]merge sort @ Python
import sysclass mergesort(): def merge_sort(self, A, p, r): if p < r: q = (p + r) / 2 self.merge_sort(A, p, q) self.merge_sort(A, q+1, r) self.merge(A, p, q, r) return A def merge(self, A, p, q, r): n1 = q - p + 1 n2 = r - q L = [0 for i in range(n1+1)] R = [0 for i in range(n2+1)] for i in range(n1): L[i] = A[p+i] for j in range(n2): R[j] = A[q+j+1] L[n1] = sys.maxint R[n2] = sys.maxint i = 0; j = 0 for k in range(p, r): if L[i] <= R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1sort = mergesort()A = [1,3,5,7,9,2,4,6,8,10]print sort.merge_sort(A, 0, len(A)-1)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。