Open In App

Time and Space Complexity of Insertion Sort

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

What is Insertion Sort?

Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed in the correct position in the sorted part.

To sort an array of size N in ascending order iterate over the array and compare the current element (key) to its predecessor, if the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

Insertion Sort Algorithm

Time Complexity of Insertion Sort Algorithm:

Best Case: O(N)

  • The best-case time complexity of Insertion Sort occurs when the input array is already sorted.
  • In this scenario, each element is compared with its preceding elements until no swaps are needed, resulting in a linear time complexity.
  • Therefore, the best-case time complexity is O(N), where n is the number of elements in the array.

Average Case: O(N2)

  • The average-case time complexity of Insertion Sort is also O(N2).
  • This complexity arises from the nature of the algorithm, which involves pairwise comparisons and swaps to sort the elements.
  • Although the exact number of comparisons and swaps may vary depending on the input, the average-case time complexity remains quadratic.

Worst Case: O(N2)

  • The worst-case time complexity of Insertion Sort occurs when the input array is in reverse sorted order.
  • In this scenario, each element needs to be compared and possibly swapped with every preceding element, resulting in a quadratic time complexity.
  • Therefore, the worst-case time complexity is O(N2), where n is the number of elements in the array.

Auxiliary Space Complexity of Insertion Sort Algorithm:

The auxiliary space complexity of Insertion Sort is O(1), indicating it uses constant extra space regardless of the input size.

This is because the algorithm typically performs in-place sorting, meaning it rearranges the elements within the input array itself without requiring additional data structures or memory allocation proportional to the input size. Therefore, regardless of the size of the input array, the amount of extra space used by the Insertion Sort algorithm remains constant.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads