I have an implementation of the Insertionsort algorithm where in the lecture there is a new instance variable before the while loop.
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
def ins_sort(l):
for i in range(len(l)):
j = i
while j > 0 and l[j - 1] > l[j]:
swap(l, j - 1, j)
j = j - 1
return l
In my testing and playing around the algorithm worked without it as well though and I do not understand why I would need to write an extra line of code if it is not necessary.
def swap(l, i, j):
temp = l[i]
l[i] = l[j]
l[j] = temp
def ins_sort(l):
for i in range(len(l)):
while i > 0 and l[i - 1] > l[i]:
swap(l, i - 1, i)
i = i - 1
return l