Write a python program for implementing insertion sort
Share
Write a python program for implementing insertion sort
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Explanation:
1)Create a function insertion_sort that takes a list as argument.
2) Inside the function create a loop with a loop variable i that counts from 1 to the length of the list – 1.
3) Set temp equal to the element at index i.
4)
Set j equal to i – 1.
def insertion_sort(lst):
for i in lst:
j = lst.index(i)
while j > 0:
if lst[j - 1] > lst[j]:
lst[j - 1], lst[j] = lst[j], lst[j - 1]
else: break
j = j - 1