Created
January 4, 2016 18:59
-
-
Save whroman/50d330730a9bc77236fa to your computer and use it in GitHub Desktop.
Javascript Array Insertion Sort
This file contains 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
var insertionSort = function () { | |
var sortedArray = []; | |
var argLen = arguments.length; | |
while (argLen--) { sortedArray = sortedArray.concat(arguments[argLen]); } | |
var newArr = []; | |
newArr.push(sortedArray[0]); | |
sortedArray.slice(1, sortedArray.length).forEach(function (itemToSort) { | |
var iter = newArr.length - 1; | |
for (iter; iter >= 0; iter--) { | |
if (itemToSort > newArr[iter]) { | |
newArr.splice(iter + 1, 0, itemToSort); | |
iter = 0; | |
} else if (iter === 0) { | |
newArr.unshift(itemToSort); | |
} | |
} | |
}); | |
return newArr; | |
}; | |
var foo = insertionSort( | |
[1,2,3,4,11], | |
[5,6,7,8] | |
); | |
console.log(foo); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment