DEV Community

Dumb Down Demistifying Dev
Dumb Down Demistifying Dev

Posted on • Edited on

3 3

Insertion Sort

What do we understand about Insertion Sort?

  • It uses 2 loops (outer for-loop & inner while-loop) and 2 pointers
  • 1st pointer starts from 1 item after the 2nd pointer
  • 2nd pointer starts from 1 item before 1st pointer
  • 2nd loop loops decrementally till 0
  • as long as current value is more than left side value we copy the left side over to current
  • insertion happens after the 2nd loop is finished
  • Mutation is performed on the original Array
  • Time complexity
    • Best -> O(n)
    • Average -> O(n^2)
    • Worst -> O(n^2)
  • Space complexity
    • O(1)
    function InsertionSort(arr) {
        for (let i = 1; i < arr.length ; i++) {
            let currentValue = arr[i];
            let oneIndexBefore = i - 1;
            while (oneIndexBefore >= 0 && arr[oneIndexBefore] > currentValue) {
                arr[oneIndexBefore + 1] = arr[oneIndexBefore];
                oneIndexBefore--;
            }
            arr[oneIndexBefore + 1] = currentValue;
        }
        return arr;
    }
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay