Insertion Sort

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Insertion Sort builds a sorted prefix and inserts the next element in the correct position (shifting).

Best case with already sorted data: $O(n)$. Worst case $O(n^{2})$. Stable and good for small or nearly sorted arrays.

Input shape Shifts (qualitative)
already sorted few
reversed many
## Where used

Nearly sorted data, small n, inner loop of hybrid sorters (TimSort uses Insertion Sort on runs). Therefore, Insertion Sort remains practically relevant.

Depth

Insertion Sort maintains an already sorted prefix. The next element is temporarily stored, larger prefix elements are shifted to the right, and the created gap takes in the element. After each round, the prefix has grown by one position and remains sorted.

The work closely corresponds to the number of inverse pairs, that is, the pairs that are out of order relative to the target order. Nearly sorted data thus create few shifts. Strongly reversed order, on the other hand, leads to a long shift chain per round.

Difficulty levels

  1. Insert an element into a sorted prefix.
  2. Connect shifts with the number of inversions.
  3. Maintain stability through the exact comparison condition.

Pitfalls

If equal elements are shifted as well, the order of equivalent records may change. Often the temporarily stored element is also lost if overwritten directly in the array.

University approvals: 0
Tasks
Question 1

Best-case time complexity of Insertion Sort:

Question 2

Which input property reduces the number of shifts in Insertion Sort?

Question 3

Implement Insertion Sort in ascending order.

Hint

A while loop can move the index backwards. Array elements are shifted by assigning to a[index].

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy