Insertion Sorting
The problem
Given an array of integers called nums, sort the array in non-decreasing order using the insertion sort algorithm and return the sorted array.
A sorted array in non-decreasing order is an array where each element is greater than or equal to all preceding elements in the array.
**Input: **nums = [7, 4, 1, 5, 3] Output: [1, 3, 4, 5, 7] Explanation: 1 <= 3 <= 4 <= 5 <= 7. Thus the array is sorted in non-decreasing order.
**Input: **nums = [5, 4, 4, 1, 1] Output: [1, 1, 4, 4, 5] Explanation: 1 <= 1 <= 4 <= 4 <= 5. Thus the array is sorted in non-decreasing order.
Input: nums = [3, 2, 3, 4, 5]
- 1 <= nums.length <= 1000
- -104 <= nums[i] <= 104
- nums[i] may contain duplicate values.
cpp
class Solution {
public:
vector<int> insertionSort(vector<int>& nums) {
}
};java
class Solution {
public int[] insertionSort(int[] nums) {
}
}python
class Solution:
def insertionSort(self, nums):javascript
class Solution {
insertionSort(nums) {
}
}csharp
public class Solution {
public int[] InsertionSort(int[] nums) {
}
}go
func insertionSort(nums []int) []int {
//your code goes here
}Stuck? Show a way to structure it+
- 01Treat the first element as a sorted prefix.
- 02Take the next value as key.
- 03Shift larger prefix values right.
- 04Insert key into the created gap.
- 05Repeat through the array.
Reference answer
Then expect these follow-ups
Why is insertion sort stable?
Tests: correctness reasoning
When is insertion sort preferable to merge sort?
Tests: follow-up reasoning
Hiring now
Software engineer roles are open right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Senior Software Engineer -.NET
Tyler Technologies · Annapolis, Maryland

Software Development Engineer II
SaaS Labs · Bengaluru, Karnataka, India

Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)
Metropolitan Transportation Authority · New York, NY
Next question