-
Notifications
You must be signed in to change notification settings - Fork 127
/
cocktail-sort.java
49 lines (41 loc) · 1.23 KB
/
cocktail-sort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Alogrithm for Cocktail Sort to sort element in ascending order
import java.util.Arrays;
public class CocktailSort {
public static void sort(int[] array) {
boolean swapped = true;
int start = 0;
int end = array.length;
while (swapped) {
swapped = false;
for (int i = start; i < end - 1; i++) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
swapped = false;
end--;
for (int i = end - 1; i >= start; i--) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
start++;
}
}
}
class CocktailSortEvaluator {
public static void main(String[] args) {
int[] array = {9,3,6,1,4};
CocktailSort.sort(array);
System.out.println(Arrays.toString(array));
}
}