DevPath

← All problems

Insertion Sort

Easy sorting · arrays

Description

Return the array sorted in ascending order using insertion sort.

Constraints

0 <= n <= 100000

Examples

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

Output: [1,2,3,4,5,6]

Hints (1)
  • Grow a sorted prefix by inserting each next element into place.

Solutions

Insert each element into the sorted prefix. · Time O(n^2) · Space O(1)

func insertionSort(nums []int) []int {
    a := append([]int{}, nums...)
    for i := 1; i < len(a); i++ {
        key := a[i]
        j := i - 1
        for j >= 0 && a[j] > key {
            a[j+1] = a[j]
            j--
        }
        a[j+1] = key
    }
    return a
}

Create a free account to submit solutions, track progress and save problems.

Create account