INSERTION-SORT(A) for j = 2 to A.length key = A[j] //inster A[j] into the sorted sequence A[1..j-1] i = j-1 while i>0 and A[i]>key A[i+1] = A[i] i = i-1 A[j+1] = key
python 实现
1 2 3 4 5 6 7 8 9
definsertion_sort(A): for j in range(1,len(A)): key = A[j] i = j-1 while i>-1and A[i]>key: A[i+1] = A[i] i -= 1 A[i+1] = key return A
练习
2.1-2 重写INSERTION-SORT,使之按降序排序。
1 2 3 4 5 6 7 8 9
definsertion_sort(A): for j in range(1,len(A)): key = A[j] i = j-1 while i>-1and A[i]<key: # 将原来的A[i]>k改为 A[i]<k A[i+1] = A[i] i -= 1 A[i+1] = key return A
MERGE(A, p, q, r) n1 = q - p + 1 n2 = r - q let L[1..n1 + 1] and R[1..n2 + 1] by new arrays for i = 1 to n1 L[i] = A[p + i -1] for j = 1 to n2 R[j] = A[q + j] L[n1 + 1] = & infin; L[n2 + 1] = & infin; i = 1 j = 1 for k = p to r if L[i] <= R[j] A[k] = L[i] i = i + 1 else A[k] = R[j] j = j + 1
1 2 3 4 5 6
MEGRE-SORT(A, p, r) if p < r q = [(p+r)/2] MEGRE-SORT(A, p, q) MEGRE-SORT(A, q+1, r) MERGE(A, p, q, r)
middle = len(A)//2 left = sort(A[:middle]) right = sort(A[middle:]) # 治 return merge(left,right)
# 治 defmerge(left,right): c = [] h = j = 0 while j<len(left) and h<len(right): if left[j]<right[h]: c.append(left[j]) j+=1 else: c.append(right[h]) h+=1
if j==len(left): for i in right[h:]: c.append(i) if h==len(right): for i in left[j:]: c.append(i)