What is the Insertion Sort in DSA ? with Free Notes

What is the Insertion Sort ?

Insertion Sort is a simple and intuitive comparison-based sorting algorithm. It builds the final sorted array one element at a time. It is much like sorting playing cards in yours hands; you take on card and insert it into its correct position relative to the already sorted cards.

Key Characteristics

  1. Time Complexity : – O(n2) in the worst case and average case: O(n) in the best case when the array is already sorted. ‘
  2. Space Complexity : – O(1) : (in place sorting)
  3. Stability : – Stable (does not change the relative order of equal elements).
  4. Algorithm Type : – Comparison-Based Sorting

How Insertion Sort Work ???

  1. Start with the First Element.
    • Consider the First Element as Sorted.
  2. Insert the next element into sorted portion.
    • Take the next element from the unsorted portion.
    • Compare it with the element in the sorted portion.
    • Shift the element in the sorted portion to the right to make space for the new element.
    • Insert the new element in the correct position.
  3. Repeat
    • Move to the next element and repeat in its process until the entire array is sorted.
Insertion Sort in DSA

Steps and Example

Consider the Following unsorted array: –

[5, 3, 8, 4, 2]

Pass 1

  • The First Element “5” is already sorted.

Pass 2

  • Take “3” and Compare it with “5”.
  • Since “3” is smaller than “5”, insert “3” before “5”.
  • Array Now : [3, 5, 8, 4, 2]

Pass 3

  • Take “8” and compare it with “5”.
  • Since “8” is larger than “5”, it remains in its position.
  • Array Now : [3, 5, 8, 4, 2]

Pass 4

  • Take “4” and compare it with “8”.
  • Since “4” is smaller than “8”, move “8” to the right.
  • Compare “4” with “5”, since “4” is smaller, move “5” to the right.
  • Insert “4” before “5”.
  • Array Now : [3, 4, 5, 8, 2]

Pass 5

  • Take “2” and compare it with “8”.
  • Since “2” is smaller than “8”, move “8” to the right.
  • Compare “2” with “5”, since “2” is smaller, move “5” to the right.
  • Compare “2” with “4”, since “2” is smaller, move “4” to the right.
  • Insert “2” before “3”.
  • Array Now : [2, 3, 4, 5, 8]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top