File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 ) {
You can’t perform that action at this time.
0 commit comments