×

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

Reason for Python So Popular

One of the languages that is witnessing outstanding development and acceptance every year in Python. Python has emerged as the programming language with the greatest rate of growth, and Stack...

3 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.

Python String zfill() method

Python String zfill() method The string.zfill() method in Python returns a copy of the string while adding the zeros (0) at the beginning of the string, until it reaches the specified...

1 minute read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

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

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

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.

Python Line Break

Introduction In this tutorial, you will learn line breaks in python.In Python, the new line character is used to indicate the start of a new line and the end of an...

5 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Division in Python

In this tutorial, we will understand what mathematical operation division is and how is it performed in Python Programming language. We will also focus on the operators being used in...

3 minutes read.