From a471c0224b885295460d1dbb61a26d4353fa455e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E5=9D=A4?= Date: Tue, 29 May 2018 17:44:14 +0800 Subject: [PATCH 1/2] fix error comments --- Sorts/src/sort/BubbleSort.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sorts/src/sort/BubbleSort.java b/Sorts/src/sort/BubbleSort.java index 99f63907..1173245f 100644 --- a/Sorts/src/sort/BubbleSort.java +++ b/Sorts/src/sort/BubbleSort.java @@ -43,12 +43,12 @@ class BubbleSort implements SortAlgorithm { BubbleSort bubbleSort = new BubbleSort(); bubbleSort.sort(integers); - // Output => 1 4 6 9 12 23 54 78 231 + // Output => 231, 78, 54, 23, 12, 9, 6, 4, 1 print(integers); // String Input String[] strings = {"c", "a", "e", "b","d"}; - //Output => a b c d e + //Output => e, d, c, b, a print(bubbleSort.sort(strings)); } From ba57c1d734ec18edb6786b6a51b05d48b3322024 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B5=B5=E5=9D=A4?= Date: Tue, 29 May 2018 19:31:56 +0800 Subject: [PATCH 2/2] reimplement CocktailShakerSort --- Sorts/src/sort/CocktailShakerSort.java | 61 ++++++++++++-------------- 1 file changed, 29 insertions(+), 32 deletions(-) diff --git a/Sorts/src/sort/CocktailShakerSort.java b/Sorts/src/sort/CocktailShakerSort.java index b5da0df5..7982b8fc 100644 --- a/Sorts/src/sort/CocktailShakerSort.java +++ b/Sorts/src/sort/CocktailShakerSort.java @@ -18,39 +18,36 @@ class CocktailShakerSort implements SortAlgorithm { * Sorts the array in increasing order **/ - @Override - public > T[] sort(T[] array){ + @Override + public > T[] sort(T[] array) { - int last = array.length; - - // Sorting - boolean swap; - do { - swap = false; - - //front - for (int count = 0; count <= last - 2; count++) { - if (less(array[count + 1], array[count])) { - swap = swap(array, count, count + 1); - } - } - //break if no swap occurred - if (!swap) { - break; - } - swap = false; - - //back - for (int count = last - 2; count >= 0; count--) { - if (less(array[count + 1], array[count])) { - swap = swap(array, count, count + 1); - } - } - last--; - //end - } while (swap); - return array; - } + int length = array.length; + int left = 0; + int right = length - 1; + int swappedLeft, swappedRight; + while (left < right) { + // front + swappedRight = 0; + for (int i = left; i < right; i++) { + if (less(array[i + 1], array[i])) { + swap(array, i, i + 1); + swappedRight = i; + } + } + // back + right = swappedRight; + swappedLeft = length - 1; + for (int j = right; j > left; j--) { + if (less(array[j], array[j - 1])) { + swap(array, j - 1, j); + swappedLeft = j; + } + } + left = swappedLeft; + } + return array; + + } // Driver Program public static void main(String[] args) {