Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Last active January 19, 2016 06:17
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 remarkablemark/c0201d560c28e6dfba4d to your computer and use it in GitHub Desktop.
Save remarkablemark/c0201d560c28e6dfba4d to your computer and use it in GitHub Desktop.
Sorting algorithms written in JavaScript.
'use strict';
/**
* Sorts an array using the insertion algorithm.
*
* @param {Array} array - The array to be sorted.
* @return {Array}
*/
function insertionSort(array) {
if (array.constructor !== Array) {
return null;
}
var arr = array.slice(0), i, len, j;
for (i = 1, len = arr.length; i < len; i++) {
for (j = 0; j < i; j++) {
if (arr[i] < arr[j]) {
arr.splice(j, 0, arr.splice(i, 1)[0]);
break;
}
}
}
return arr;
}
/**
* Module exports.
*/
if (typeof module !== 'undefined' && module.exports) {
module.exports = insertionSort;
}
'use strict';
/**
* Merges two arrays in ascending order.
*
* @param {Array} leftArray - The first array.
* @param {Array} rightArray - The second array.
* @return {Array}
*/
function merge(leftArray, rightArray) {
if (leftArray.constructor !== Array && rightArray.constructor !== Array) {
return null;
}
var left = leftArray.slice(0),
right = rightArray.slice(0),
result = [];
while (left.length > 0 || right.length > 0) {
if (left[0] <= right[0] || right.length === 0) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result;
}
/**
* Sorts the array using the merge (divide-and-conquer) algorithm.
*
* @param {Array} array - The array to be sorted.
* @return {Array}
*/
function mergeSort(array) {
if (array.constructor !== Array) {
return null;
}
var arr = array.slice(0),
len = arr.length,
left, right;
if (array.constructor === Array && len < 2) {
return array;
}
left = arr.splice(0, len / 2);
right = arr;
left = mergeSort(left);
right = mergeSort(right);
return merge(left, right);
}
/**
* Module exports.
*/
if (typeof module !== 'undefined' && module.exports) {
module.exports = mergeSort;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment