Elementary sorting methods

This week in my IPM, the stories were about algorithms and sorting methods!

I started with a simple question: what is an algorithm? And I found a simple answer: a set of steps to accomplish a task.

Jarkyn asked me to look up the sorting method called Bubble Sort and make a kata out of it. In my next blog post, I will talk about it and explain how I did it.

But first, what are the elementary sorting methods:

  • Selection sort:

Let’s jump to an example to explain how this method works

Given the following array [5, 4, 3, 1, 2],
 — Pick the smallest element in the search range (the whole array here) and swap positions with the first element,
The new array is [1, 4, 3,5 , 2], this array is not sorted yet.

— Given the new array [1, 4, 3, 5, 2], pick the smallest element in the search range (from number 4 to 2) and swap position with the second element,
The new array is [1, 2, 3, 5, 4], this array is not sorted yet.

— Given the new array [1, 2, 3, 5, 4], pick the smallest element in the search range (from number 3 to 4) and swap positions with the third element, nothing happens as 3 is the smallest element
Arrays stays unchanged: [1, 2, 3, 5, 4] and is still not sorted.

— Given the same array [1, 2, 3, 5, 4] pick the smallest element in the search range (from number 4 to 5) and swap position with the fourth element,
The new array is [1, 2, 3,4, 5]

  • Insertion sort:

Let’s jump to an example to explain how this method works

— Given the following array [5, 4, 3, 1, 2] take the first two elements, sort them in ascending order.
The new array is [4,5, 3, 1, 2]

— Given the new array [4,5, 3, 1, 2], sort this range [4,5, 3] in ascending order.
The new array is [3, 4,5, 1, 2]

Given array [3, 4,5, 1, 2], sort this range [3, 4,5, 1] in ascending order
The new array is [1, 3, 4,5, 2]

Given array [1, 3, 4,5, 2], sort this range [1, 3, 4,5, 2] in ascending order
The new array is [1, 2, 3,4,5]