Program for Insertion sort using Python


In insertion sort is similar to the sorting methodology we use while playing card games. The given array is split into sorted and unsorted parts and element from unsorted part is picked and moved to correct place in sorted part.

Program for Insertion sort using Python


def sort(ip_arr):
    for i in range(1, len(ip_arr)):
        k = ip_arr[i]
        j = i - 1
        while j >= 0 and k < ip_arr[j]:
            ip_arr[j + 1] = ip_arr[j]
            j -= 1
        ip_arr[j + 1] = k
ip_arr = [89, 121, 101, 6]
print("The input array is: ", ip_arr)
print("Sorted array is :")
for i in range(len(ip_arr)):
    print("%d" %ip_arr[i])


Program for Insertion sort using Python Output


The below steps are followed for insertion sort:

  1. Iterate elements from index[1] to index[n].
  2. Compare ele[i] to ele[i-1], if ele[i] < ele[i-1] compare ele[i] and ele[i-2]. Swap with the greater element.
  3. Continue the steps 1 and 2 until all the elements are sorted.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.