Skip to content
Onsite

Insertion Sort

EasyP2Coding

Sort an array of integers in ascending order using insertion sort and return the sorted array.

Insertion sort keeps a sorted prefix. For each next element, shift larger prefix elements one place to the right and drop the element into the gap. Write the algorithm yourself instead of calling a built-in sort.

Example 1

Input
nums = [5,2,4,6,1,3]
Output
[1,2,3,4,5,6]

Example 2

Input
nums = [1,2,3]
Output
[1,2,3]

Example 3

Input
nums = []
Output
[]

Constraints

  • 0 <= nums.length <= 1000
  • -10^4 <= nums[i] <= 10^4

Hints

Run checks the 3 visible tests, Submit all 9.