
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program for Insertion Sort
In this article, we will learn about the implementation of the Insertion sort in Python 3.x. Or earlier.
Algorithm
1. Iterate over the input elements by growing the sorted array at each iteration. 2. Compare the current element with the largest value available in the sorted array. 3. If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position in the array. 4. This is achieved by shifting all the elements towards the right, which are larger than the current element, in the sorted array to one position ahead.
Now let’s see the visual representation of the algorithm −
Now let’s see the implementation
Example
def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are greater than key, # to one position ahead of their current position j = i-1 while j >=0 and key < arr[j] : arr[j+1] = arr[j] j -= 1 arr[j+1] = key # main arr = ['t','u','t','o','r','i','a','l'] insertionSort(arr) print ("The sorted array is:") for i in range(len(arr)): print (arr[i])
Output
The sorted array is: a i l o r t t u
Time Complexity − O(n*2)
Auxiliary Space − O(1)
All the variables are declared in the global frame as shown in the figure below −
Conclusion
In this article, we learned about the Insertion sort and its implementation in Python 3.x. or earlier.
- Related Articles
- Python Program for Binary Insertion Sort
- Python Program for Recursive Insertion Sort
- Insertion Sort in Python Program
- C Program for Recursive Insertion Sort
- Java Program for Binary Insertion Sort
- Java Program for Recursive Insertion Sort
- C++ Program Recursive Insertion Sort
- Java program to implement insertion sort
- C++ Program to Implement Insertion Sort
- What is Insertion sort in Python?
- Insertion Sort
- Golang Program To Sort An Array In Ascending Order Using Insertion Sort
- Golang Program to sort an array in descending order using insertion sort
- Python Program for Bubble Sort
- Python Program for Selection Sort

Advertisements