×

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 object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

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

7 minutes read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Python range() function

Python range() function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Syntax range(stop)        or range(start, stop[, step]) Parameter start: It is...

1 minute read.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

Python sorted() function

Python sorted() function The sorted() function returns a sorted list of the specified iterable object. Syntax sorted(iterable, *, key=None, reverse=False) Parameter iterable: It is a required parameter that represents the sequence to sort, list, dictionary, tuple etc. key:...

1 minute read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

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

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.