×

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or descending order. Insertion sort is one way to do it. In this sorting technique, the array is divided into two parts. One is the sorted array, and the other is the unsorted array. We pick one element from the unsorted part of the array and place that element in its correct position in the sorted part of the array.

The implementation of insertion sort is quite easy and simple. It is an in-place sorting technique which means it does not need any extra space for sorting the elements. It sorts the elements in the same memory space in which the input elements are sorted. It is also a stable sorting technique meaning that the elements get sorted in the order in which they are entered in the array. For example, if we have the same multiple elements in the array, the element that comes first in the unsorted array will also come first in the sorted array.

  • The array elements are traversed from the first to the last index. In other words, we can say that the array is traversed from 1 to n.
  • If the array element at position i is greater than its predecessor, which is the element at (i-1)th index, it does not need to be moved.
  • If the array element at position i is less than its predecessor, which is the element at (i-1)th index, it needs to be moved or shifted towards the left until we find a predecessor which is smaller than it or if we reach the first element or the leftmost position in the array.

Code for insertion sort using python

def insertion_sort(arr):
 
    # Traverse the array from the first to the last element
    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
 
list1 = [11,7,43,22,3,19]
insertion_sort(list1)   
list2 = [] 
print("Sorted array is : ")
for i in range(1, len(list1)):
  list2.append(list1[i])       
print(list2)

Output

Sorted array is : 
[7, 11, 19, 22, 43]

Explanation

In the above code set, we have created a function called insertion_sort(arr). Inside the function, we defined for loop for traversing the array from the first element to the last element or traversing the element from 1 to len(arr). In for loop, assigned a value of arr is key. Every time the loop iterates, the new value will assign to the variable value key. Now, we have used another variable, and we have used the while to check whether the j is greater or equal to 0 and the value is smaller than the first element of the list. If both conditions are true, then we will move the first element to the 0th index and reduce the value of j by one index, and so on. In the end, we will copy the value of the list1 to another list named list2 and print the result.

Time Complexities

  • Worst Case Complexity for Insertion Sort is O(n2).
    The worst-case scenario occurs in insertion sort when an array is in ascending order, and you want to sort it in the opposite order, descending order. In this case, worst-case complexity occurs. In that case, each element has to be compared with the other elements, so, for every nth element, n-1 comparisons are made. Thus, the total number of comparisons = n*(n-1). This is equivalent to n2.
  • Best Case Complexity for Insertion Sort is O(n).
    The worst-case scenario occurs in insertion sort when the array is already sorted in the desired order, and the outer loop runs for n number of times, whereas the inner loop does not run at all because the condition will fail each time. So, there is only n number of comparisons. Thus, complexity is linear.
  • Average Case Complexity for Insertion Sort is O(n2).
    It occurs when the elements of an array are in mixed order, neither ascending nor descending.
  • Space Complexity

Space complexity is O(1) because an extra variable is used.

Application of Insertion Sort

The insertion sort is mostly used when the array has less number of elements and when there are only a few elements left to be sorted.


Related Topics

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

GUI Calendar using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

3 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Python Basics

In this tutorial, we will learn about the basics of Python, a very famous programming language. This tutorial will help you understand the language better if you start with python....

8 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.