doc = "unsorted.txt"
out_fil = "H:\Grade 11\Intro to Computer Science\sorted.txt" # Used in the Windows variation of the program
out_file = "/Applications/Banter" # Used in the Mac variation of the program
import time
def main():
order = False
blank = []
passcount = 0
starttime = time.time()
numlist = CreateList(doc)
while not order:
passcount = passcount + 1
switch = False
switchcount = 0
print "1" # These are test prints to I used to find problems
for x in range (len(numlist)):
print "2" # These are test prints to I used to find problems
if numlist[x] > numlist[x+1]:
temp = numlist[x+1]
numlist[x+1] = numlist[x]
numlist[x] = temp
switchcount = switchcount + 1
switch = True
print "9" # These are test prints to I used to find problems
elif switch == 0:
order = True
CreateFile(numlist)
endtime = time.time()
print "This list required",endtime-starttime,"seconds to sort."
print "This list required",switchcount,"switches to sort."
print "This list required",passcount,"passes to sort."
def CreateList(doc):
sort = open(doc,"r")
numlist = sort.readlines()
sort.close()
for x in range (len(numlist)):
numlist[x] = int(numlist[x].strip())
return numlist
def CreateFile(numlist):
sort = open(doc,"w")
sort.write(str(numlist)+"\n")
sort.close()
return numlist
def List(numlist):
print numlist
main()
我的程序的主要目的是使用冒泡排序方法按顺序对文件中的整数列表进行排序,然后将该列表放入新文件中。我还详细说明了执行此操作所需的时间以及完全对其进行排序所需的程序中的通过次数和切换次数。
现在,我遇到的问题是列表索引超出了范围,因为它比较了我的numlist的x和x + 1。但是,我需要比较x + 1,以便对列表中彼此旁边的两个整数进行排序。有没有什么方法可以修复程序,以便它比较列表中的所有整数,而不是因为x + 1而没有尝试比较列表中的空格?
答案 0 :(得分:1)
你可以用这种方式制作你的循环:
for x in range ( len(numlist) -1 ):
答案 1 :(得分:0)
虽然stackoverflow是一个很好的答案资源,但是让他们做作业作业就像是在作弊。我会半途遇见你:让你的循环运行少一次迭代。