Code of the day – Javascript Insertion Sort

Insertion Sort.
Best: O(n), Average: O(n2), Worst: O(n2)
Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time.
Visit Wikipedia for more information.

Code

//Programmer: Larry Battle Mar 9, 2011
//Purpose: Insertion sort implemented in Javascript.
var insertionSort = function (arr) {
    var len = arr.length, i = -1, j, tmp;

    while (len--) {
        tmp = arr[++i];
        j = i;
        while (j-- && arr[j] > tmp) {
            arr[j + 1] = arr[j];
        }
        arr[j + 1] = tmp;
    }
};

Usage

insertionSort( [5,4,3,2,1] ); //returns [1,2,3,4,5];
insertionSort( [ "bear", "dog", "cat" ] ) // returns ["bear", "cat", "dog"];

Demo

Jsbin.com
bateru.com/uploads

Here’s a great short video tutorial to help those clueless about insertion sort.


Update:

/**
* Sorts an array using insertion sort.
* 
* @param {Array} - arr
* @param {Boolean} areNumbers indicates whether the array elements should be cast as numbers.
* @return {Array} the sorted array.
*/
var insertionSort = function (arr, areNumbers) {
	arr = arr.concat();
	var len = arr.length,
	i = -1,
	j,
	tmp;
	while (len--) {
		tmp = arr[++i];
		j = i;
		while (j-- && areNumbers ? (+arr[j] > +tmp) : (arr[j] > tmp) ) {
			arr[j + 1] = arr[j];
		}
		arr[j + 1] = tmp;
	}
	return arr;
};
// Treat input as array of numbers
Input: insertionSort(["1","2","3","4","4","40","20","21"], true);
Output: ["1", "2", "3", "4", "4", "20", "21", "40"]

// Treat input as array of strings
Input: insertionSort(["1","2","3","4","4","40","20","21"]);
Output: ["1", "2", "20", "21", "3", "4", "4", "40"]

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

View Comments

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago