DEV Community

Cover image for Insertion Sort (JS Example)
Clean Code Studio
Clean Code Studio

Posted on • Edited on

2 2

Insertion Sort (JS Example)

Twitter Follow

Note: This is not a "professionally written" post. This is a post sharing personal notes I wrote down while preparing for FAANG interviews.

See all of my Google, Amazon, & Facebook interview study notes


Insertion Sort Breakdown

  • Worst Complexity: n^2
  • Average Complexity: n^2
  • Best Complexity: n
  • Space Complexity: 1
  • Method: Insertion
  • Stable: Yes

Insertion Sort Notes

Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Wikipedia

Insertion Sort JavaScript Implementation

const InsertionSort = (items = []) => {
    for (let i = 1; i < items.length; i++)
    {
      let index = i-1
      let temporary = items[i]

      while (index >= 0 && items[index] > temporary)
      {          
        items[index + 1] = items[index]
        index--
      }
      items[index + 1] = temporary
    }

    return items
}

module.exports = InsertionSort
Enter fullscreen mode Exit fullscreen mode

FAANG Study Resource: Cracking the Coding Interview
(Google Recommended)


My FAANG interview study notes

Insertion Sort Github

Clean Code

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
cleancodestudio profile image
Clean Code Studio

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay