Python Insertion Sort Program using Array

By | March 20, 2020

Python Insertion Sort Program using Array

# Write a Python program insertion sort
# to input n numbers in
# python array and sort them
# in ascending order using insertion sort algorithm
# Perfect Python Programming Tutorials
# Author : (c)

import array

# define a function for insertion sort

def insertion_sort(arr): 
    for i in range(1, len(arr)): 
        key = arr[i] 
        j = i-1
        while j >=0 and key < arr[j] : 
                arr[j+1] = arr[j] 
                j -= 1
        arr[j+1] = key 
# end of insertion sort

# main

# Define array of integer numbers
a = array.array('i', [])

n = int(input('Enter  size of Array='))
# input n numbers in arry
for i in range(n):
    item= int(input("Enter number in array:"))

# call insertion_sort() function for sorting array

# print sorted array
print ("Sorted array is:")
for i in a:
    print (i, '\t')


Enter  size of Array=5
Enter number in array:900
Enter number in array:780
Enter number in array:564
Enter number in array:234
Enter number in array:111
Sorted array is:


One thought on “Python Insertion Sort Program using Array

  1. Pingback: Array Numbers Factorials in C++ |

Leave a Reply

Your email address will not be published. Required fields are marked *