Insertion Sorting

Asked atAmazon
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

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+
  1. 01Treat the first element as a sorted prefix.
  2. 02Take the next value as key.
  3. 03Shift larger prefix values right.
  4. 04Insert key into the created gap.
  5. 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

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question