×

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 SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Event Key in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Find Words in String Python

Python : Python programming language is considered a general purpose; it is a high-level programming language that is not much difficult but easier to learn. Python programming language is rich in...

5 minutes read.

Working with CSV files in Python

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...

7 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Standard GUI Unit Converter using PyQt5 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...

6 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Python Parser

Introduction : Parsing is referred to as the processing and translation of a Python program into machine language. In general, we could indeed say that the command parse is used to...

4 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.