michaelp0730
1/4/2015 - 5:45 PM

Insertion Sort JavaScript

var a = [34, 27, 16, 2, 99, 109, 31, 80, 21];
var names = ['Michael', 'Jessica', 'Ava', 'Elise', 'Enzo'];
var strings = ['ZzZ', 'zZz', 'qQq', 'QqQ', 'BbB', 'bBb', 'aAa', 'AaA'];

function insertionSort(items) {

    var len     = items.length,     // number of items in the array
        value,                      // the value currently being compared
        i,                          // index into unsorted section
        j;                          // index into sorted section
    
    for (i=0; i < len; i++) {
    
        // store the current value because it may shift later
        value = items[i];
        
        /*
         * Whenever the value in the sorted section is greater than the value
         * in the unsorted section, shift all items in the sorted section over
         * by one. This creates space in which to insert the value.
         */
        for (j=i-1; j > -1 && items[j] > value; j--) {
            items[j+1] = items[j];
        }

        items[j+1] = value;
    }
    
    return items;
}