标签:== 冒泡 end 逆序对 str ati for lse return
《算法导论》第二章,讨论了归并排序,其中思考题2-4提出了逆序对问题,需要注意边界条件:
# inversion 逆序对 A =[3,1,4,5,2,-3,6] def inversion(arr): ‘‘‘ 冒泡版 ‘‘‘ invs = [] for i in range(len(arr)): for j in range(i): if arr[j] > arr[i]: invs.append(str(arr[j])+‘,‘+str(arr[i])) return invs allinvs = [] def inversionmerge(arr): ‘‘‘ 归并版 ‘‘‘ if len(arr)==1: return arr m = int((len(arr) +1)/2) arr1 = inversionmerge(arr[0:m]) arr2 = inversionmerge(arr[m:len(arr)]) return merge(arr1,arr2) def merge(arr1, arr2): arr = [] i1, i2 = 0, 0 l = len(arr1) + len(arr2) for k in range(l): if i1==len(arr1) and i2 == len(arr2): break if i1 >= len(arr1): arr.append(arr2[i2]) i2+=1 continue if i2 >= len(arr2): arr.append(arr1[i1]) # 逆序 for n in range(len(arr1)-1, i1+1, -1): allinvs.append(formatinvs(arr1[n],arr2[i2-1])) i1+=1 continue if arr1[i1] < arr2[i2]: arr.append(arr1[i1]) i1+=1 else: arr.append(arr2[i2]) # 逆序 for m in range(len(arr1)-1, i1-1, -1): allinvs.append(formatinvs(arr1[m],arr2[i2])) i2+=1 return arr def formatinvs(a,b): return str(a)+‘,‘+str(b) def main(): print(inversion(A)) inversionmerge(A) print(allinvs) if __name__ == "__main__": main()
标签:== 冒泡 end 逆序对 str ati for lse return
原文地址:https://www.cnblogs.com/ShengunErshu/p/13174412.html