Reputation: 1
I'm learning Python from a web source which implemented the Insertion Sort algorithm using a combination of for loop and while loop. I thought of practicing the code by myself and I coded an algorithm using only for loops. I need some feedback on whether my code is correct, and whether its valid.
def insertionSort(lst):
for i in range(1,len(lst)):
temp = lst[i]
for j in range(0,i):
if lst[j] > temp:
lst[i], lst[j] = lst[j], lst[i]
return lst
lst = [8, 6, 4, 20, 24, 2, 10, 12]
print(insertionSort(lst))
The output is: [2, 4, 6, 8, 10, 12, 20, 24]
Upvotes: 0
Views: 314
Reputation: 350167
Your algorithm could be called insertion sort in a broad sense, but it is different from what is commonly understood by insertion sort, as it compares the temp
value with all previous values, while standard insertion sort only compares temp
with the greater values among the previous values, and with one additional value that will become temp
's predecessor (if there is one).
This means your implementation will have a best case time complexity that is O(𝑛²), while the best case time complexity of the standard algorithm is O(𝑛). That best case occurs when the input is already sorted.
The typical insertion sort algorithm will have the inner loop going backwards, visiting values in descending order, and stopping when it finds a value that is less than (or equal to) the value to move (temp
). During this loop the swaps are done with 2 consecutive values, and this can be improved by delaying the insertion of temp
so that values only have to be copied one place to the right until the insertion point is found.
An implementation of that in Python could look like this:
def insertionSort(lst):
for i, temp in enumerate(lst):
for j in range(i - 1, -1, -1):
if lst[j] <= temp: # Found insertion point?
lst[j + 1] = temp
break
lst[j + 1] = lst[j] # Make room for temp
else: # temp is the least value so far: insert at the start
lst[0] = temp
return lst
To test yourself whether your implementation correctly sorts a list, you can bombard your function with random input. For instance like this:
import random
for size in range(100):
lst = list(range(size))
random.shuffle(lst)
finallist = lst[:]
insertionSort(finallist)
if finallist != sorted(finallist):
print("Not sorted correctly:", lst, "to", finallist)
break
else:
print("All tests passed successfully")
Upvotes: 1