Articles

Program to implement insertion sort in Python

Program to implement insertion sort in Python


In the python programming article, we are going to learn

  • program to implement insertion sort in python

Program to implement insertion sort in Python

The program to implement insertion sort in python is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

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 
    
    return arr


if __name__ == "__main__":
    marks = [22,66,43,58,98,42,77,56,66]
    result = insertion_sort(marks)

    print("The sorted marks: ", result)

The output of the program is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
The sorted marks:  [22, 42, 43, 56, 58, 66, 66, 77, 98]

Few important tips about the program

1. This is an in-place comparison based sorting algorithm.

2. The list is searched sequentially  and unsorted items are moved and inserted into the sorted sublist.

3. It is very less efficient for bigger lists.

 

insertion sort in python

 


Basic Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :    Published Date : Oct 13,2022  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!