Implement insertion sort in Python

PHOTO EMBED

Tue Jun 18 2024 03:23:53 GMT+0000 (Coordinated Universal Time)

Saved by @pynerds #python

def insertion_sort(lst):
   for i in range(1, len(lst)):
      j = i
      while (j > 0) and lst[j-1] > lst[j]:
         lst[j-1], lst[j] = lst[j], lst[j-1] #swap the elements
         j -=1

#sort a list
L = [5, 2, 9, 3, 6, 1, 0, 7, 4, 8]
insertion_sort(L)
print("The sorted list is: ", L)
content_copyCOPY

https://www.pynerds.com/data-structures/implement-insertion-sort-in-python/