Javascript Data Structure Tutorial - Javascript Insertion Sort








The insertion sort has two loops.

The outer loop moves element by element through the array, while the inner loop compares the element chosen in the outer loop to the element next to it in the array.

Example


function MyArray(numElements) { //from w  w  w. j a v a2  s  .com
    this.dataStore = []; 
    this.pos = 0; 
    this.numElements = numElements; 
    this.insert = insert; 
    this.toString = toString; 
    this.clear = clear; 
    this.setData = setData; 
    this.swap = swap; 
    this.insertionSort = insertionSort;
    for (var i = 0; i < numElements; ++i) { 
        this.dataStore[i] = i; 
    } 
} 

function setData() { 
    for (var i = 0; i < this.numElements; ++i) { 
        this.dataStore[i] = Math.floor(Math.random() * (this.numElements+1)); 
    } 
} 

function clear() { 
    for (var i = 0; i < this.dataStore.length; ++i) { 
        this.dataStore[i] = 0; 
    } 
} 
function insert(element) { 
    this.dataStore[this.pos++] = element; 
} 
function toString() { 
    var retstr = ""; 
    for (var i = 0; i < this.dataStore.length; ++i) { 
        retstr += this.dataStore[i] + " "; 
        if (i > 0 && i % 10 == 0) { 
            retstr += "\n"; 
        } 
    } 
    return retstr; 
} 
function swap(arr, index1, index2) { 
    var temp = arr[index1]; 
    arr[index1] = arr[index2]; 
    arr[index2] = temp; 
} 
function insertionSort() { 
    var temp, inner; 
    for (var outer = 1; outer <= this.dataStore.length-1; ++outer) { 
        temp = this.dataStore[outer]; 
        inner = outer; 
        while (inner > 0 && (this.dataStore[inner-1] >= temp)) { 
            this.dataStore[inner] = this.dataStore[inner-1]; 
            --inner; 
        } 
        this.dataStore[inner] = temp; 
    } 
} 

var numElements = 10; 
var mynums = new MyArray(numElements); 
mynums.setData(); 
console.log(mynums.toString()); 
mynums.insertionSort(); 
console.log(); 
console.log(mynums.toString()); 

The code above generates the following result.