def countInversion(arrayList):
if len(arrayList)==1:
return (0,arrayList)
halfIndex=int(len(arrayList)/2.0)
countA,sortedA=countInversion(arrayList[:halfIndex])
countB,sortedB=countInversion(arrayList[halfIndex:])
returnList=[]
i=0
j=0
countInter=0
for index in range(0,len(arrayList)):
if i<len(sortedA) and j<len(sortedB):
if sortedA[i]<sortedB[j]:
returnList.append(sortedA[i])
i+=1
else:
returnList.append(sortedB[j])
j+=1
countInter+=len(sortedA)-i
elif i<len(sortedA):
returnList.append(sortedA[i])
i+=1
elif j<len(sortedB):
returnList.append(sortedB[j])
j+=1
return (countA+countB+countInter,returnList)
f=open('IntegerArray.txt','r')
listAll=[]
for line in f.readlines():
listAll.append(int(line))
f.close()
print listAll
countAll,sortedAll=countInversion(listAll)
print countAll#,sortedAll
合并两个子list计算inversions的时候,要注意是加上sortedA所有剩下的元素数量。
程序在windows下运行十分缓慢,大约20分钟过去还没有运行完毕,但在linux下不过一秒就运行结束。其中的原因有待推敲。
分享到:
相关推荐
python-algorithms-mastering-basic-algorithms-in-the-python-language.9781430232377.53502.pdf
python-algorithms-mastering-basic-algorithms-in-the-python-language(英文正版)1
Algorithm-Problem-Solving-with-Algorithms-and-Data-Structures-using-Python.zip,使用python的算法和数据结构解决问题的代码,算法是为计算机程序高效、彻底地完成任务而创建的一组详细的准则。
Chapter 1 - The Role of Algorithms in Computing Chapter 2 - Getting Started Chapter 3 - Growth of Functions Chapter 4 - Recurrences Chapter 5 - Probabilistic Analysis and Randomized ...
problem-solving-with-algorithms-and-data-structure-using-python 中文版
A-Comparative-Study-of-Reco-mmendation-Algorithms-in-E-Commerce-Applications
Chapter 1 - The Role of Algorithms in Computing Chapter 2 - Getting Started Chapter 3 - Growth of Functions Chapter 4 - Recurrences Chapter 5 - Probabilistic Analysis and Randomized ...
Beginning Algorithms----学习算法的好书,介绍各种算法!!!
Chapter 1 - The Role of Algorithms in Computing Chapter 2 - Getting Started Chapter 3 - Growth of Functions Chapter 4 - Recurrences Chapter 5 - Probabilistic Analysis and Randomized ...
Neo4j,用户手册,涵盖所有集成的图算法及应用场景,非常适合图算法的学习和应用
Chapter 1 - The Role of Algorithms in Computing Chapter 2 - Getting Started Chapter 3 - Growth of Functions Chapter 4 - Recurrences Chapter 5 - Probabilistic Analysis and Randomized ...
Chapter 1 - The Role of Algorithms in Computing Chapter 2 - Getting Started Chapter 3 - Growth of Functions Chapter 4 - Recurrences Chapter 5 - Probabilistic Analysis and Randomized ...
遗传算法Python程序 Hands-On-Genetic-Algorithms-with-Python-master.zip
Multicore DSP_From Algorithms to Real-time Implementation on the TMS320C66x SoC
《Introduction to Algorithms》---MIT教材 本书自第一版出版以来,已经成为世界范围内广泛使用的大学教材和专业人员的标准参考手册。本书全面论述了算法的内容,从一定深度上涵盖了算法的诸多方面,同时其讲授和...
近似算法关于np问题,很经典的一部著作,可以好好研究近似算法关于np问题,很经典的一部著作,可以好好研究近似算法关于np问题,很经典的一部著作,可以好好研究
Approximation algorithms 近似算法 - Vazirani.pdf
Algorithms for hyper-parameter optimization.pdf,讲述贝叶斯算法的TPE过程的专业论文
Data Structures And Algorithms With Object-oriented Design Patterns In Java.chm