Created
December 9, 2017 16:54
-
-
Save scriptonian/43bef4856c6818b4640854d4de58daed to your computer and use it in GitHub Desktop.
Javascript Insertion Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ScriptoniteSort() { | |
this.arr = []; | |
} | |
ScriptoniteSort.prototype = { | |
swap: function(arr, index_one, index_two) { | |
//swap | |
var temp = arr[index_one]; | |
arr[index_one] = arr[index_two]; | |
arr[index_two] = temp; | |
}, | |
validateCollection: function(datalist) { | |
if(arguments.length === 0 || !Array.isArray(this.arr)) { | |
throw new Error('Either No Arguments Passed, Or Passed Param is not an Array'); | |
} | |
}, | |
insertionSort : function(datalist) { | |
//assign the data property to the passed in datalist | |
this.arr = datalist; | |
//check if passed in is an array | |
this.validateCollection(datalist); | |
//set length of array | |
var dataLength = this.arr.length; | |
for (var i = 1; i < dataLength; i++) { | |
var temp = this.arr[i]; | |
//placeholder is where we will insert | |
var placeHolderIndex = i; | |
while( (placeHolderIndex > 0) && (this.arr[placeHolderIndex-1] > temp) ) { | |
//if condition is met then keep shifting the values | |
this.arr[placeHolderIndex] = this.arr[placeHolderIndex-1]; | |
placeHolderIndex--; | |
} | |
this.arr[placeHolderIndex] = temp; | |
} | |
console.log("Insertion Sort Result: ", this.arr.toString()); | |
} | |
}; | |
//var myArr = [9, 11, 5, 1, 7, 2, 15, 1]; | |
//var myArr = [1, 7, 4, 0, 5, 3]; | |
var myArr = [64, 25, 12, 22, 11]; | |
var collection = new ScriptoniteSort(); | |
collection.selectionSort(myArr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment