diff --git a/algorithms/sorting/shaker-sort/shaker-sort.js b/algorithms/sorting/shaker-sort/shaker-sort.js new file mode 100644 index 0000000..5347028 --- /dev/null +++ b/algorithms/sorting/shaker-sort/shaker-sort.js @@ -0,0 +1,41 @@ +/** + * 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 shaker sort implementation in JavaScript. + * @param {Array} items An array of items to sort. + * @return {Array} The sorted array. + */ +function shakerSort(items) { + var start = 0, + end = items.length - 1, + i; + + do { + + for (i = end; i > 0; i--) { + if (items[i-1] >= items[i]) { + swap(items, i, i-1); + start = i + 1; + } + } + + for (i = 1; i <= start; i++) { + if (items[i-1] > items[i]) { + swap(items, i, i-1); + end = i - 1; + } + } + + } while (start < end); +} 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; +}