Skip to main content

Why InsertionSort = SelectionSort?

· 2 min read
Strider

SelectionSort is a sorting method, which works in-place, here no new array is created for the sorting. SelectionSort works in bestcase, averagecase and worstcase, with an overhead of O(n2)O(n^2).

I mentioned that both InsertionSort and SelectionSort are the same. Why this is so I want to show here.

Both methods have a similar structure but different approaches.

A box

We imagine a box. This box has 2 inputs and 2 outputs. At the inputs, I can put in different numbers. At the outputs, the numbers come out in sorted order.

A small sketch of the box.

box.png

A trinangle of boxes

And now let's imagine that we have several of the boxes. The smartest way would be to arrange them like a triangle. This would look like this, for example.

sort1.png

If we now specify a few numbers on the left side, we get the numbers sorted out again at the bottom. And this is exactly where both methods are hiding.

Where is SelectionSort?

We know that SelectionSort always searches for the minimum when sorting.

sort2.png

Where is InsertionSort?

InsertionSort inserts the elements directly into the correct position when sorting. Here you can see this in the lines.

sort3.png

Here you can say that both methods are the same despite different approaches. Magic, that's funny 😄

I hope I was able to clarify why both are the same 😄