´╗┐Python-courses-neighborhood-Python-courses-bin-Python-courses-python-string

Exercise 55

Write an algorithm in Python to sort a list according to the insertion sort algorithm.

Solution

# Python insertion sort algorithm
def sort_insertion (tab):
# Browse from 1 to tab size
for i in range (1, len (tab)):
k = tab [i]
j = i-1
while j >= 0 and k <tab [j]:
tab [j + 1] = tab [j]
j = j - 1
tab [j + 1] = k
return tab
# Test de l'algorithme
tab = [18, 11, 23, 55, 7, 63, 17, 33]
print(sort_insertion (tab))
#The output: [7, 11, 17, 18, 23, 33, 55, 63]
Younes Derfoufi
my-courses.net

Leave a Reply