I made my own version of insertion sorting, which uses pop and insert - to select the current element and insert it before the smallest element larger than the current one - instead of the standard swap back until an element of a larger size is found. When I run two on my computer, mine is about 3.5 times faster. However, when we did this in class, everything was much slower, which is really confusing. Anyway, here are two functions:
def insertionSort(alist):
for x in range(len(alist)):
for y in range(x,0,-1):
if alist[y]<alist[y-1]:
alist[y], alist[y-1] = alist[y-1], alist[y]
else:
break
def myInsertionSort(alist):
for x in range(len(alist)):
for y in range(x):
if alist[y]>alist[x]:
alist.insert(y,alist.pop(x))
break
Which one should be faster? Does it alist.insert(y,alist.pop(x))resize listback and forth, and how does this affect time efficiency?
Here is my pretty primitive test of two functions:
from time import time
from random import shuffle
listOfLists=[]
for x in range(100):
a=list(range(1000))
shuffle(a)
listOfLists.append(a)
start=time()
for i in listOfLists:
myInsertionSort(i[:])
myInsertionTime=time()-start
start=time()
for i in listOfLists:
insertionSort(i[:])
insertionTime=time()-start
print("regular:",insertionTime)
print("my:",myInsertionTime)