Here is how to sort using Insertion Sort in Python?
Run the code here: https://repl.it/@VinitKhandelwal/insertion-sort
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run the code here: https://repl.it/@VinitKhandelwal/insertion-sort
def insertionSort(list1):
n = len(list1)
for i in range(1, n):
index = i
for j in reversed(range(0, i)):
if list1[i] < list1[j]:
index = j
else:
break
if index == i:
pass
else:
temp = list1[i]
list1[index+1:i+1] = list1[index:i]
list1[index] = temp
return list1
print(insertionSort([5,3,8,1,9,0,2,4,7,6]))
print(insertionSort([9,8,7,6,5,4,3,2,1,0])) # O(n^2)
OUTPUT
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Comments
Post a Comment