from time import clock import sys def main(): start=clock() try: f=open('10_1.txt','r') f1=open('out_11_10_1c.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") j=0 q=len(a) while(j < q-j): minindex = j maxindex=q-j-1 for k in xrange(j + 1, q-j): if int(a[k]) <= int(a[minindex]): if int(a[minindex]) > int(a[maxindex]): maxindex=minindex ncomp+=2 minindex = k elif int(a[k])>int(a[maxindex]): maxindex=k ncomp+=2 min=int(a[minindex]) max=int(a[maxindex]) if j == maxindex : a[minindex] = a[q-j-1] a[q-j-1]=min a[maxindex] = a[q-j-1] a[q-j-1]=max nswap+=2 ncomp+=1 j+=1 continue elif k == minindex: a[maxindex] = a[j] a[j]=max a[minindex] = a[j] a[j]=min nswap+=2 ncomp+=1 j+=1 continue elif j!=minindex or k!=maxindex: if j != minindex: a[minindex]=a[j] a[j]=min nswap+=1 if k!=maxindex: a[maxindex]=a[k] a[k]=max nswap+=1 ncomp+=1 j+=1 continue for d in xrange(0,q-1): write(str(int(a[d]))+",") write(str(int(a[q-1]))+"\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(maxindex)+sys.getsizeof(max)+sys.getsizeof(min)+sys.getsizeof(d)+sys.getsizeof(q) write("\nMemory used by the program is : %d bytes." %mem) f1.close() except IOError: print "Input file not found in the directory." main()