ExamAdda Logo

Insertion Sort

Easy

Given an integer array nums of size n, sort the array in ascending order using the Insertion Sort algorithm.

Insertion Sort builds the sorted array one element at a time by taking each element from the unsorted portion and inserting it into its correct position in the sorted portion.

Return the sorted array.

Example 1

Input

5
12 11 13 5 6

Output

5 6 11 12 13

Explanation

Insertion Sort starts from the second element and inserts each element into its correct position in the already sorted left portion of the array.

After processing all elements, the array becomes sorted.

Example 2

Input

6
6 5 4 3 2 1

Output

1 2 3 4 5 6

Explanation

Each element is shifted to make space for the current element until it reaches its correct position in the sorted portion.

Constraints

1 ≤ n ≤ 10³
-10⁵ ≤ nums[i] ≤ 10⁵

Hints:

Hint 1

Assume the first element is already sorted. Start from the second element and insert it into its correct position in the sorted part of the array.

Hint 2

Shift all elements greater than the current element one position to the right, then insert the current element into the vacant position.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Jul 21, 2026

Last updated

Aug 6, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output