from time import clock import sys def main(): start=clock() try: f=open('10_1.txt','r') f1=open('out_11_10_1a.txt','w') f.readline() ncomp=0 #To count the number of comparisons. nswap=0 #To count the number of swappings. write=f1.write #In python, local variables are easier to access than global ones. If f1.write() is invoked multiple times, it will call the write function from the library everytime. #Therefore, using local variable, write() will be call from library just once and later using the local variable.""" for i in xrange(1,6): #xrange() is used instead of range() as it is a generator object which does not create any object immediately like range(), but rather when you pull from the generator. a=[] a=f.readline().split(",") lstrip=a[0].lstrip a[0]=lstrip("Set"+str(i)+":") f.readline() write("\nSorted Set"+str(i)+":\n") for j in xrange(0, len (a)): minindex = j for k in xrange(j + 1, len(a)): if int(a[k]) < int(a[minindex]): ncomp+=1 minindex = k else: ncomp+=1 if j != minindex : a[j], a[minindex] = a[minindex], a[j] nswap+=1 if(j!=len(a)-1): write(str(int(a[j]))+",") pp=len(a)-1 write(str(int(a[pp]))+"\n") f.close() end=clock() write("\nTime taken by the program is : %f seconds" %(end-start)) write("\nThere are %d comparisons in the program." %ncomp) write("\nThere are %d swappings in the program." %nswap) mem = sys.getsizeof(f) + sys.getsizeof(f1)+ sys.getsizeof(i)+ sys.getsizeof(a)+ sys.getsizeof(nswap) + sys.getsizeof(ncomp)+ sys.getsizeof(i)+ sys.getsizeof(j)+ sys.getsizeof(k)+sys.getsizeof(minindex)+sys.getsizeof(pp) write("\nMemory used by the program is : %d bytes." %mem) f1.close() except IOError: print "Input file not found in the directory." main()