Inserting And Sorting Stuff(Sorting JS)

Insertion Sorting

This is article is on my continual escapade on this dynamically typed language called  JavaScript.

As you progress through this valley of shadow and death that is JS developing and debugging you will realize there is no bad language only bad programs.So if you must learn , learn it well.

So let’s start with how all this works.

BASIC :We need to sort through a list arranging in either ascending or descending orderbut the tricky thing is taking least time and least space.Just One shoe fits all doesn’t work here some of the Sorting algorithms may be better than other but there are best case and worst case for each of them.(Ascending Order for example).

Step 1: Take the i’th(i=2) element compare with the previous element .

Step 2:If i-1 ‘th (i-1=1)element is greater then overwrite the i’th on i-1 ‘th .

Step 3:Do that fori-2 ‘th element and so on until there are no elements left before i.

Step 4:increment the value of i and repeat the steps 1 to 3 until the end of array is reached .You can see this stratergy working in this gif down below.
https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gifzz

function insertItSempai(arr){
  var key;
  for(var j=1;j<arr.length;j++){     
    key=arr[j];
    i=j-1;     
    while(i>=0&&arr[i]>key)
      {
        
        arr[i+1]=arr[i];
        i--;
        
      }
    arr[i+1]=key;
  }
  return arr;
  
}
console.log(insertItSempai([2,3,5,6,4,12,435]));

Run this in the console of your Google Chrome browser or Mozilla FireFox

(Open Console by pressing  Ctrl +F12 then clicking on the console tab.)

(Cautionary Waring :If you DON’T TRY THIS AT HOME it may be harmful to your future as a developer.)

Enjoy.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s