Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Insertion Sort in Python

Insertion Sort in Python

Posted on February 12, 2025February 12, 2025 By Rishabh saini No Comments on Insertion Sort in Python

Insertion Sort in Python

Sorting algorithms play a crucial role in computer science, and Insertion Sort is one of the most fundamental yet effective techniques, especially for small datasets. It is more efficient than Bubble Sort and operates similarly to sorting playing cards in hand.

In this blog post, we will explore Insertion Sort, understand its working mechanism, implement it in Python, and analyze its time complexity. Let’s get started!

Complete Python Course with Advance topics:-Click here

What is Insertion Sort?

Insertion Sort is an in-place, stable sorting algorithm that is simple yet useful for nearly sorted data or small-sized arrays. It builds a sorted list one element at a time by inserting each item into its correct position relative to the already sorted portion of the array.

Key Properties:

  • In-place: Requires no extra space; sorting happens within the array itself.
  • Stable: Maintains the relative order of equal elements.
  • Efficient for small datasets: Works best when the number of elements is less than 10.
  • Adaptive: Performs well when the array is nearly sorted.

Concept of Insertion Sort

Insertion Sort splits the array into two virtual parts:

  1. Sorted Part – Initially contains the first element of the array.
  2. Unsorted Part – Contains the rest of the array.

The algorithm picks an element from the unsorted part and inserts it into its correct position in the sorted part, shifting larger elements to the right.

Steps to Perform Insertion Sort:

  1. Assume the first element is already sorted.
  2. Pick the next element and compare it with elements in the sorted part.
  3. Shift larger elements one position to the right to create space.
  4. Insert the picked element into the correct position.
  5. Repeat until all elements are sorted.

Let’s see an example.

Example Walkthrough

Given an unsorted array:

[10, 4, 25, 1, 5]

Sorting Process:

  1. The first element 10 is considered sorted.
  2. Pick 4. Since 4 < 10, shift 10 to the right and insert 4 before it: [4, 10, 25, 1, 5]
  3. Pick 25. It is greater than 10, so it remains in place: [4, 10, 25, 1, 5]
  4. Pick 1. Shift 25, 10, and 4 rightward and insert 1 at the beginning: [1, 4, 10, 25, 5]
  5. Pick 5. Shift 25 and insert 5 before 10: [1, 4, 5, 10, 25]

Now, the array is sorted!

Python Implementation

Here’s how we can implement Insertion Sort in Python:

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

# Testing the function
arr = [10, 5, 13, 8, 2]
print("Unsorted List:", arr)
print("Sorted List:", insertion_sort(arr))

Output:

Unsorted List: [10, 5, 13, 8, 2]
Sorted List: [2, 5, 8, 10, 13]

Explanation:

  1. The function loops through the array starting from index 1.
  2. It picks an element and shifts the larger elements one position to the right.
  3. It inserts the picked element in its correct place.
  4. The loop continues until the entire array is sorted.

Sorting Custom Objects

Python allows sorting of objects using Insertion Sort by defining a custom comparison function. Below is an example of sorting points based on their x coordinate.

# Point Class
def insertion_sort(arr, compare_func):
    for i in range(1, len(arr)):
        value = arr[i]
        j = i - 1
        while j >= 0 and compare_func(arr[j], value):
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = value

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return f"({self.x}, {self.y})"

points = [Point(2,3), Point(4,4), Point(3,1), Point(8,0), Point(5,2)]

# Sorting by x-coordinate
insertion_sort(points, lambda a, b: a.x > b.x)
for point in points:
    print(point)

Output:

(2,3)
(3,1)
(4,4)
(5,2)
(8,0)

Time Complexity

Insertion Sort is not ideal for large datasets due to its O(n²) time complexity.

CaseComplexity
Best Case (Nearly Sorted)O(n)
Average CaseO(n²)
Worst Case (Reversed Order)O(n²)

Despite this, it is efficient for small datasets and is used in Shell Sort as a subroutine.

Space Complexity:

  • O(1) (Since it does not use additional storage apart from the input array)

Download New Real Time Projects :-Click here
Complete Advance AI topics:- CLICK HERE

Conclusion

Insertion Sort is a simple, stable, and in-place sorting algorithm. Although inefficient for large datasets, it is useful in scenarios where data is nearly sorted. We have covered its working principle, Python implementation, sorting custom objects, and time complexity analysis.

For more programming tutorials, visit UpdateGadh—your go-to platform for coding insights and solutions!


Insertion Sort in Python
selection sort in python
insertion sort algorithm
insertion sort in python with example
insertion sort in python using list
insertion sort in python using for loop
insertion sort in python user input
insertion sort in java
Insertion Sort in Python
insertion sort in python without using function
python compiler
insertion sort in python w3schools

Post Views: 509
Python Interview Question Tags:insertion sort, insertion sort algorithm, insertion sort algorithm python, insertion sort code in python, insertion sort in python, insertion sort in python explained, insertion sort in python using for loop, insertion sort program in python, insertion sort python, insertion sort python code, insertion sort using list in python, insertion sorting in python, Python, python insertion sort, python insertion sort algorithm, sorting in python

Post navigation

Previous Post: SQL ORDER BY LIMIT – Retrieve Specific Rows from a Database
Next Post: SQL INSERT STATEMENT

More Related Articles

How to Round Numbers in Python How to Round Numbers in Python Python Interview Question
for Loop in Python How to Use for Loop in Python: A Comprehensive Guide Python Interview Question
How to Declare a Global Variable in Python How to Declare a Global Variable in Python Python Interview Question

Leave a Reply Cancel reply

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

You may also like

  1. How to Install Python on Windows: A Step-by-Step Guide
  2. How to Run Python Program: A Comprehensive Guide for Python Programmers
  3. How to Append Elements to a List in Python
  4. How to Declare a Global Variable in Python
  5. How to Clear the Python Shell
  6. How to Print Patterns in Python

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,612)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,210)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,862)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme