Skip to content

Commit ba57c1d

Browse files
author
赵坤
committed
reimplement CocktailShakerSort
1 parent a471c02 commit ba57c1d

File tree

1 file changed

+29
-32
lines changed

1 file changed

+29
-32
lines changed

Sorts/src/sort/CocktailShakerSort.java

Lines changed: 29 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -18,39 +18,36 @@ class CocktailShakerSort implements SortAlgorithm {
1818
* Sorts the array in increasing order
1919
**/
2020

21-
@Override
22-
public <T extends Comparable<T>> T[] sort(T[] array){
21+
@Override
22+
public <T extends Comparable<T>> T[] sort(T[] array) {
2323

24-
int last = array.length;
25-
26-
// Sorting
27-
boolean swap;
28-
do {
29-
swap = false;
30-
31-
//front
32-
for (int count = 0; count <= last - 2; count++) {
33-
if (less(array[count + 1], array[count])) {
34-
swap = swap(array, count, count + 1);
35-
}
36-
}
37-
//break if no swap occurred
38-
if (!swap) {
39-
break;
40-
}
41-
swap = false;
42-
43-
//back
44-
for (int count = last - 2; count >= 0; count--) {
45-
if (less(array[count + 1], array[count])) {
46-
swap = swap(array, count, count + 1);
47-
}
48-
}
49-
last--;
50-
//end
51-
} while (swap);
52-
return array;
53-
}
24+
int length = array.length;
25+
int left = 0;
26+
int right = length - 1;
27+
int swappedLeft, swappedRight;
28+
while (left < right) {
29+
// front
30+
swappedRight = 0;
31+
for (int i = left; i < right; i++) {
32+
if (less(array[i + 1], array[i])) {
33+
swap(array, i, i + 1);
34+
swappedRight = i;
35+
}
36+
}
37+
// back
38+
right = swappedRight;
39+
swappedLeft = length - 1;
40+
for (int j = right; j > left; j--) {
41+
if (less(array[j], array[j - 1])) {
42+
swap(array, j - 1, j);
43+
swappedLeft = j;
44+
}
45+
}
46+
left = swappedLeft;
47+
}
48+
return array;
49+
50+
}
5451

5552
// Driver Program
5653
public static void main(String[] args) {

0 commit comments

Comments
 (0)