Skip to content

Instantly share code, notes, and snippets.

@whroman
Created January 4, 2016 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whroman/50d330730a9bc77236fa to your computer and use it in GitHub Desktop.
Save whroman/50d330730a9bc77236fa to your computer and use it in GitHub Desktop.
Javascript Array Insertion Sort
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