diff --git a/algorithms/sorting/insertion-sort/binary-insertion-sort.js b/algorithms/sorting/insertion-sort/binary-insertion-sort.js new file mode 100644 index 0000000..b09ee17 --- /dev/null +++ b/algorithms/sorting/insertion-sort/binary-insertion-sort.js @@ -0,0 +1,30 @@ +/** + * An binary insertion sort implementation in JavaScript. + * @param {Array} items An array of items to sort. + * @return {Array} The sorted array. + */ + +function binaryInsertionSort(items) { + var len = items.length, + left, right, center, i, item; + + for (i = 1; i < len; i++) { + left = 0; + right = i - 1; + + while (left < right) { + center = Math.floor((left + right) / 2); + if (items[center] > items[i]) { + right = center; + } else { + left = center + 1; + } + } + + // Remove element from array and paste to new position + item = items.splice(i, 1)[0]; + items.splice(left, 0, item); + } + + return items; +} diff --git a/algorithms/sorting/shell-sort/shell-sort.js b/algorithms/sorting/shell-sort/shell-sort.js new file mode 100644 index 0000000..d80554e --- /dev/null +++ b/algorithms/sorting/shell-sort/shell-sort.js @@ -0,0 +1,39 @@ +/** + * Swaps two values in an array. + * @param {Array} items The array containing the items. + * @param {int} firstIndex Index of first item to swap. + * @param {int} secondIndex Index of second item to swap. + * @return {void} + */ +function swap(items, firstIndex, secondIndex){ + var temp = items[firstIndex]; + items[firstIndex] = items[secondIndex]; + items[secondIndex] = temp; +} + +/** + * A shell sort implementation in JavaScript. + * @param {Array} items An array of items to sort. + * @return {Array} The sorted array. + */ +function shellSort(items) { + var len = items.length + step = len, + i, j; + + do { + step = Math.floor(step/2); + i = 0; + j = i + step; + while (j < len) { + if (items[i] > items[j]) { + swap(items, i, j); + } + + i++; + j = i + step; + } + } while (step >= 1); + + return items; +}