Insertion Sort Program in Python

Written by

Himani Kohli

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:

  1. Define a function named insort(a) that takes in a list a.
  2. Inside the function, use a for loop to iterate through each element in the list, starting from the second element (index 1).
  3. For each element, store it in a variable b.
  4. Use a while loop to iterate backwards through the list, starting at the current index and ending at the beginning of the list.
  5. 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.
  6. Decrement the index by 1 at the end of each iteration of the while loop.
  7. After the for loop completes, the list will be sorted in ascending order.
  8. 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
Insertion Sort Program in Python