0
0
DSA Goprogramming~3 mins

Why Insertion Sort Algorithm in DSA Go?

Choose your learning style9 modes available
The Big Idea

What if you could sort your messy list just like arranging cards one by one perfectly?

The Scenario

Imagine you have a messy stack of playing cards and you want to arrange them in order by their numbers.

If you try to do this by randomly picking cards and guessing where they go, it will take a long time and be confusing.

The Problem

Trying to sort items manually by guessing their correct position is slow and easy to mess up.

You might lose track of cards or place them in the wrong order, making the whole process frustrating.

The Solution

Insertion Sort helps by taking one card at a time and placing it exactly where it belongs among the already sorted cards.

This way, the stack stays organized as you go, making sorting simple and clear.

Before vs After
Before
for i := 0; i < len(cards); i++ {
    for j := 0; j < len(cards); j++ {
        if cards[i] < cards[j] {
            // swap cards[i] and cards[j]
        }
    }
}
After
for i := 1; i < len(cards); i++ {
    key := cards[i]
    j := i - 1
    for j >= 0 && cards[j] > key {
        cards[j+1] = cards[j]
        j--
    }
    cards[j+1] = key
}
What It Enables

Insertion Sort enables you to sort items step-by-step, keeping the list organized as you insert each new item.

Real Life Example

When organizing books on a shelf one by one, you pick each book and place it in the right spot among the already arranged books.

Key Takeaways

Manual sorting is slow and error-prone.

Insertion Sort places each item in the correct position as you go.

This method keeps the list sorted at every step.