Introduction
Hello World! Similar to most other programming languages, you can run into scenarios where you have to sort a bunch of data.
Firstly, let's get it out of the way. When we say "sort", the idea is to re-arrange the elements such that they are in ascending order.
If you are new to the concept of sorting, each section of the article would be useful. However, If you are here to refresh your knowledge, jump straight to the javascript implementation of the sort.
There are at least 8 different sorting algorithms in JavaScript. In order to keep this blog short but still full of helpful knowledge, I will be focusing on the following algorithm for now:
- Insertion Sort
And in the next blog, I'll be focusing on the other three sorting algorithms:
- Bubble Sort
- Merge Sort
- Quick Sort
I believe the best way for us to learn about this subject is to visually understand how each algorithm does the sorting per each iteration of the loop.
Insertion Sort
Insertion sort is a very simple algorithm that works best for data that is already mostly sorted.
The basic idea is that we select one element at a time and then search for the correct place to insert it. Hence the name, insertion sort. This results in the array having two parts — the sorted part of the array and the elements that have yet to be sorted. Some like to picture this as two different arrays — one with all of the unsorted elements and a new one that is entirely sorted. However, picturing it as one array is more true to how the code works.
Let’s take a look at the code block and then discuss it.
Code Explained
- We send an unsorted array into our function.
for (var i = 1, i< length; i++ )
makes a loop from the index 1 tolen - 1
. So, we don't use the first element for the loop.key = arr[i]
saves the value in a variable.key
is the "current value" which we are going to insert.j = i - 1
, initial j isi - 1
, which is the index right beforei
.while ( j >= 0 && arr[ j ] > key )
, loops through the elements in our array if the value of indexj
is greater than our key.arr[ j + 1 ] = arr[ j ]
, shifts the element we checked (index j) one time to the right.j--
, decreases j. So, we can examine the previous element. Ifj < 0
, the while loop ends, as we don't have more elements in our array.arr[ j + 1 ] = key
, inserts our card into the correct position. (j + 1
is used because, inside the while loop,j
decreases one more time than it should)
Loop by loop with the example
When starting to understand an algorithm that has loops, the best way is to go loop by loop with an example. It gives you an idea of what the algorithm really does.
Let's take the first loop.
[3, 1, 5, 6, 2]
is our unsorted array. (5 elements, index 0 to 4)- for loop loops from the index 1 to 4 ([1,5,6,2] elements.
First for loop :-
i
is 1key
is 1j
is 0arr[ j ]
is 3arr[j]
<key
- while loop doesn't run
So, we shift element 3 one time to the right. Now we have the array [3,3,5,6,2].
j--
. Nowj
is -1.j < 0
. So, while loop terminatesarr[j + 1] = key
equalsarr[0] = 1
.
After the first loop, we have the array [1,3,5,6,2]
Second for loop
i
is 2key
is 5j
is 1arr[ j ]
is 3arr[ j ]
<key
- while loop doesn't run
We have the same array [1,3,5,6,2] after the second for loop.
Third for loop
i
is 3key
is 6j
is 2arr[ j ]
is 5arr[ j ]
<key
- while loop doesn't run
We have the same array [1,3,5,6,2] after the second for loop.
Forth for loop
This is the interesting part.
Now we have [1, 3, 5, 6]
(sorted) in our hand. 2
is the element we are examining. We are going to insert it to the correct position.
i
is 4key
is 2j
is 3arr[ j ]
is 6arr[ j ]
>key
while loop runs
- Shifts 6 one time to the right. Now we have
[1, 3, 5, 6, 6]
. 5 > 2
, shifts 5 one time right.[1, 3, 5, 5, 6]
- '3 > 2
, shifts 3 one time right.
[1,3,3,5,6]` 1 < 2
, that's the 2's position! Insert it after 1. Now we have[1,2,3,5,6]
.
- Shifts 6 one time to the right. Now we have
We just sorted our array using insertion sort!
Benifits
- It’s stable — equal elements appear in the same order in the sorted list.
- It’s adaptive — it’s fast when sorting mostly sorted lists or when adding items to an already sorted list.
- It’s very easy to implement!
Complexity
The time complexity of this algorithm, in at worst case, is quadratic — O(n²). As n approaches infinity the average case approaches the worst-case divided by two. However since if your list is sorted or nearly so, it can be O(n) in a best-case scenario and thus well adapted to that scenario.
In my next article, we will see how Bubble sort works. See you in the next post!
I hope it helped you understand JavaScript Insertion Sort a little better. And If you have any questions, or if I got anything incorrect, please don’t hesitate to leave a comment below! :)