I have implemented insertion sort in python and was wondering how to determine the complexity of the algorithm. Is this an inefficient way of implementing insertion sort? To me, this seems like the most readable algorithm.
import random as rand
source = [3,1,0,10,20,2,1]
target = []
while len(source)!=0:
if len(target) ==0:
target.append(source[0])
source.pop(0)
element = source.pop(0)
if(element <= target[0]):
target.reverse()
target.append(element)
target.reverse()
elif element > target[len(target)-1]:
target.append(element)
else:
for i in range(0,len(target)-1):
if element >= target[i] and element <= target[i+1]:
target.insert(i+1,element)
break
print target
while len(source)!=0is equivalent towhile sourceif you know thatsourceis a list or string, etc. Also,if len(target) == 0can beif not targetbisectmoduleifstatement inside yourwhileloop to be called once. So move it out of the loop - place it before the loop. As it is now, given a one element list, your function will try to pop an element from it - twice.