Let's play cards and learn insertion sort

Let's play cards and learn insertion sort

The moment you stack your books in the shelf, or when you arrange the shirts hanging in your cupboard putting the shorter ones before the longer ones, or arrange cash in ascending order or play cards but serialize them before, you never knew you were using insertion sort all this time.

Let us follow up with an example:

Unsorted array.PNG You can clearly see that the array is partially sorted. All you need to do is pick up 7 and put it before 8. You will compare 7 with 10 and replace 7 with 10. Next you will compare 7 with 9 and shift 9 to right and so on till 7 reaches it's appropriate position.

The pictorial representation will be like this

sorted array.PNG

Let's code it now

  1. Clearly we are iterating the array in reverse order.
  2. We are storing the value of unsorted element in some temp variable.
  3. We compare the value of temp with array elements and shift the element to the right if the array element is larger than temp.
var temp = arr[i];
var j = i -1;
while(j>=0 && arr[j] > temp) {
       arr[j+1] = arr[j];
       j--;
 }
 arr[j+1] = temp;

Now the same process is repeated for every element in the array hence we will use an outer loop to do that.

for(var i=1;i<=arr.length -1; i++){
        var temp = arr[i];
        var j = i -1;
        while(j>=0 && arr[j] > temp) {
            arr[j+1] = arr[j];
            j--;
        }
        arr[j+1] = temp;
}

Let us not forget to calculate the complexity of insertion sort. The outer loop will always run so a complexity of O(n) will always be there. In best case scenario you may not need to shift the elements at all if the array is already sorted and in worst case scenario you might need to shift all elements further increasing the complexity To sum up the complexity:

complexity.PNG

That's all from my side. Do comment if you find it is easier to learn this way. Next time you sort your shirts in cupboard, keep this in mind that insertion sort is helping you out! Always!