# freeCodeCamp Challenge Guide: Implement Insertion Sort

**URL:** <https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-implement-insertion-sort/301613>\
**Category:** freeCodeCamp Contributors\
**Tags:** guide\
**Created:** [August 3, 2019, 1:23pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-implement-insertion-sort/301613 "2019-08-03T13:23:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![camperbot](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/camperbot/32/18364_2.png) [@camperbot](https://forum.freecodecamp.org/u/camperbot)\
**Post date:** [August 3, 2019, 1:23pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-implement-insertion-sort/301613/1 "2019-08-03T13:23:49Z")

</div>

# [Implement Insertion Sort](https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-insertion-sort)

* * *

## Problem Explanation

- Insertion Sort assumes that array is divided in two parts:
  1. Sorted (Initially the first element)
  2. Unsorted

- Each pass, we select an element, and check it against the sorted array.
- If the selected element is smaller than the last element of the sorted array then we shift the sorted array by 1 until we find the spot to _insert_ the selected element.
- ![Insertion sort in action](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) - [source](https://en.wikipedia.org/wiki/Insertion_sort)
- Time comlexity of Insertion sort is of **O(n2)**.
- It’s a **stable** algorithm.

* * *

## Solutions

> **Solution 1 (Click to Show/Hide)**
>
> ```js
> function insertionSort(array) {
> for (let i = 1; i < array.length; i++) {
> let curr = array[i];
> for (var j = i - 1; j >= 0 && array[j] > curr; j--) {
> array[j + 1] = array[j];
> }
> array[j + 1] = curr;
> }
> return array;
> }
> 
> ```
> 
> #### Relevant Links
> 
> - [Wikipedia](https://en.wikipedia.org/wiki/Insertion_sort)
> - [Khan Academy](https://www.youtube.com/watch?v=lCzQvQr8Utw)

---

<div class="post-metadata">

**Author:** ![ILM](https://sea3.discourse-cdn.com/freecodecamp/user_avatar/forum.freecodecamp.org/ilm/32/363239_2.png) [@ILM](https://forum.freecodecamp.org/u/ILM)\
**Post date:** [January 8, 2025, 3:57pm UTC](https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-implement-insertion-sort/301613/2 "2025-01-08T15:57:55Z")

</div>


