I have two implementations of insertion sort. The first largely transcript of the example in my java tutorial (although with a loop whileinstead of a java loop for)
def insertion_sort(array):
for i in range(1,len(array)):
j = i
while j > 0 and array[j] < array[j-1]:
array[j],array[j-1] = array[j-1], array[j]
j=j-1
return array
The second, apparently, more realistic implementation.
def insertion_sort2(array):
for i in range(1,len(array)):
for j in range(i-1,-1,-1):
if array[j+1] < array[j]:
array[j+1],array[j] = array[j],array[j+1]
else:
break
return array
After timing, both seem to be much slower (3-4 times slower) when the list is already sorted or very sorted. However, as the number of inversions increases, the second implementation seems to gain the upper hand (10-15% faster). I'm just wondering if anyone can explain what the reason for this discrepancy is. Thank!
Edit: here is the function I use to create a random list.
def rand_list(length):
return [random.randint(0,9*length) for _ in range(length)]
, , list(range(length1)) + rand_list(length2).
, , %timeit datetime.now(). . , , .