Insertion sort in JavaScript

I started reading Introduction to Algorithms to educate myself on the subject.

There are books on algorithms that are rigorous but incomplete and others that cover masses of material but lack rigor. Introduction to Algorithms combines rigor and comprehensiveness.
In order to motivate myself reading it cover to cover, I thought it’d be a good idea to blog about my progress. Beside me being “forced” to write an update every now and then, I might help somebody else in the progress. The first algorithm is solving a sorting problem. The technique is called Insertion sort. It’s suited for sorting a small number of elements and the idea is pretty simple. Insertion sort works the way many people sort a hand of playing cards. The collection is sorted from beginning to end. While looping over the elements, it compares the current element to the ones before it in the collection. All the elements that are bigger than the current element are moved one place to the right. The current element is inserted after the first element that is smaller than itself. Have a look at the Wikipedia page if you want to know more about it. In JavaScript it looks like this:
var collection = [5, 2, 4, 6, 1, 3];

for(var j = 1; j = 0 && collection[i] > key) {
		collection[i+1] = collection[i];
		i = i - 1;
	}

	collection[i+1] = key;
}
 

Wednesday, October 27, 2010   ()