How to sort an Array Using Insertion Sort DSA

Insertion Sort DSA is a simple sorting algorithm that works in similar way of playing card sorting. This algorithm splits the array into two parts, sorted and unsorted array. Values from unsorted parts are picked and placed into the correct place in sorted array.

Insertion Sort DSA
Insertion Sort DSA

Let have try the Algorithm

For example we have an array: [12, 11, 13, 5, 6], consider these elements for all examples.

Explanation:

  1. Iteration 1 (i = 1): Key = 11
    • Compare 11 with 12, since 11 < 12, shift 12 to the right.
    • Insert 11 at the correct position, which is index 0.
    • Array after iteration 1: [11, 12, 13, 5, 6]
  2. Iteration 2 (i = 2): Key = 13
    • Compare 13 with 12, no shifting needed.
    • Insert 13 at the correct position, which is index 2.
    • Array after iteration 2: [11, 12, 13, 5, 6]
  3. Iteration 3 (i = 3): Key = 5
    • Compare 5 with 13, 12, and 11. Shift 13, 12, and 11 to the right.
    • Insert 5 at the correct position, which is index 0.
    • Array after iteration 3: [5, 11, 12, 13, 6]
  4. Iteration 4 (i = 4): Key = 6
    • Compare 6 with 13, no shifting needed.
    • Insert 6 at the correct position, which is index 4.
    • Array after iteration 4: [5, 6, 11, 12, 13]

Insertion Sort Java DSA

JavaScript

Dart

Time Complexity and Auxiliary Space Analysis

Time Complexity: O(N2)

Auxiliary Space: O(1)

Thank you for reaching out us. For any query or doubt, you can comment in the section below.

See Also

Selection Sort Algorithms | How to sort an Array/List using Selection sort?

Bubble Sort DSA | Full Explanation with Examples

Factorial of a Number Full Explanation With Examples

Check Tree is a BST or not Full Explanation

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top