From df96740f5d54a299004595e174524fdbc634164f Mon Sep 17 00:00:00 2001 From: KuLi Date: Sat, 30 Sep 2017 20:34:58 +0200 Subject: [PATCH] Implemented cocktail shaker sort algorithm --- Sorts/cocktailShakerSort.js | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Sorts/cocktailShakerSort.js diff --git a/Sorts/cocktailShakerSort.js b/Sorts/cocktailShakerSort.js new file mode 100644 index 000000000..356184e7c --- /dev/null +++ b/Sorts/cocktailShakerSort.js @@ -0,0 +1,45 @@ +/* + * Cocktail shaker sort is a sort algorithm that is a bidirectional bubble sort + * more information: https://en.wikipedia.org/wiki/Cocktail_shaker_sort + * more information: https://en.wikipedia.org/wiki/Bubble_sort + * + */ +function cocktailShakerSort(items) { + + for (var i = items.length - 1; i > 0; i--) { + var swapped = false; + var temp, j; + + // backwards + for (j = 0; j > i; j--) { + if (items[j] < items[j - 1]) { + temp = items[j]; + items[j] = items[j - 1]; + items[j - 1] = temp; + swapped = true; + } + } + + //forwards + for (j = 0; j < i; j++) { + if (items[j] > items[j + 1]) { + temp = items[j]; + items[j] = items[j + 1]; + items[j + 1] = temp; + swapped = true; + } + } + if (!swapped) { + return; + } + } +} + +//Implementation of cocktailShakerSort + +var ar = [5, 6, 7, 8, 1, 2, 12, 14]; +//Array before Sort +console.log(ar); +cocktailShakerSort(ar); +//Array after sort +console.log(ar); \ No newline at end of file