Insertion Sort Program in Python
Written by
In this piece of code, we will be learning to quote our logic to implement the insertion sort using python.
It is less efficient on large lists than advanced algorithms such as quicksort, heapsort, or merge sort.
Algorithm:
- Define a function named
insort(a)
that takes in a lista
. - Inside the function, use a
for
loop to iterate through each element in the list, starting from the second element (index 1). - For each element, store it in a variable
b
. - Use a
while
loop to iterate backwards through the list, starting at the current index and ending at the beginning of the list. - Inside the
while
loop, compare the element at the current index to the element at the previous index. If the element at the current index is smaller, swap the two elements. - Decrement the index by 1 at the end of each iteration of the
while
loop. - After the
for
loop completes, the list will be sorted in ascending order. - Use a
for
loop to print each element
Code:
def insort(a):
for i in range(1, len(a)):
b = a[i]
j = i - 1
while j >= 0 and b < a[j]:
a[j], a[j + 1] = a[j + 1], a[j]
j -= 1
a = [5, 6, 4, 1, 3, 2]
insort(a)
for i in a:
print(i)
Output:
1
2
3
4
5
6