TechBask

Learn | Explore | Share | Challenge Yourself | Enjoy | Make This World Beautiful Place To Live For Everyone|

Archive for the month “July, 2014”

Insertion sort in Javascript

These days, i am on spree to dive deep into javascript. As this is the exciting time for Javascript and it is finally getting accepted as full-fledged language, i thought to explore it at low level. How its basic predefined functions work. So i thought why not implement basic data structures and algorithms in javascript.

I’ll start with Sorting algorithms and first in the series is Insertion sort. Read more about insertion sort here.

Fun fact: The javascript V8 engine, virtual machine for Chrome browser uses Insertion sort for sorting objects with less than 23 elements and for more than that it uses Quick sort.

Note: Insertion sort performs well for sorting array with small number of elements.
Complexity: O(n*n) — worst case



function insertionSort(arrayOfNumbers){
	
	for(var i = 1; i < arrayOfNumbers.length; i++){

		var temp = arrayOfNumbers[i];

		var j = i-1;

		while(arrayOfNumbers[j] > temp && j >= 0){

			arrayOfNumbers[j+1] = arrayOfNumbers[j];
			j--;
		}

		arrayOfNumbers[j+1] = temp;
	}	
}


Things i learned … the hard way

1. Life is not fair.

Believe me, you’ll be knocked down on your face, several times. Choose to dust yourself up. keep moving. You are not the only one, life f**ks us all. Some come out strong, some choose to blame. who you want to be?

Don’t try to get mercy. Stand up. Walk to rule the world.

2. No one cares about you.

Trust me. The world won’t care about your self-esteem. The world will expect you to accomplish something BEFORE you feel good about yourself. It is you, who you should depend on.

Invest in yourself. Prove it you matter.

3. Stand up for yourself.

This was hardest. Why it is that we stop loving ourself. Learn to stand up for yourself and what you believe in. It is important for your being. You are important to yourself. Don’t eat yourself away, by demeaning your Self.

Love yourself. Love should come naturally. Start with yourself.

4. Small is Great.

Does magic. Think of your next big goal – the whole thing, all at once. What happens to you sanity?. Instead Start small. Do it everyday little by little. There are no shortcuts for being awesome and sane. small will become big one day. Believe that.

Post Navigation