Skip to content

Commit 566f4e1

Browse files
committed
add Shaker Sort algorithm
1 parent 29c45d7 commit 566f4e1

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Sorts/ShakerSort.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2+
/*
3+
* https://en.wikipedia.org/wiki/Cocktail_shaker_sort
4+
*
5+
* Cocktail shaker sort,[1] also known as bidirectional bubble sort,[2] cocktail sort, shaker sort (which can also
6+
* refer to a variant of selection sort), ripple sort, shuffle sort,[3] or shuttle sort, is a variation of bubble sort
7+
* that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that
8+
* it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more
9+
* difficult to implement than a bubble sort, and solves the problem of turtles in bubble sorts. It provides
10+
* only marginal performance improvements, and does not improve asymptotic performance; like the bubble sort,
11+
* it is not of practical interest (insertion sort is preferred for simple sorts), though it finds some use
12+
* in education.
13+
*
14+
* */
15+
public class ShakerSort {
16+
17+
public static void main(String[] args) {
18+
19+
int[] arr = {13,31,4,5,3,44,23,13,23};
20+
shakerSort(arr);
21+
for (int i : arr) {
22+
System.out.println(i);
23+
}
24+
}
25+
26+
public static void shakerSort(int[] arr_) {
27+
for (int i = 0; i < arr_.length/2; i++) {
28+
boolean change = false;
29+
for (int j = i; j < arr_.length - i - 1; j++) {
30+
if (arr_[j] < arr_[j+1]) {
31+
int tmp = arr_[j];
32+
arr_[j] = arr_[j+1];
33+
arr_[j+1] = tmp;
34+
change = true;
35+
}
36+
}
37+
for (int j = arr_.length - 2 - i; j > i; j--) {
38+
if (arr_[j] > arr_[j-1]) {
39+
int tmp = arr_[j];
40+
arr_[j] = arr_[j-1];
41+
arr_[j-1] = tmp;
42+
change = true;
43+
}
44+
}
45+
if(!change) break;
46+
}
47+
}
48+
49+
50+
51+
52+
}

0 commit comments

Comments
 (0)