commit
419b91d85c
@ -43,12 +43,12 @@ class BubbleSort implements SortAlgorithm {
|
|||||||
BubbleSort bubbleSort = new BubbleSort();
|
BubbleSort bubbleSort = new BubbleSort();
|
||||||
bubbleSort.sort(integers);
|
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);
|
print(integers);
|
||||||
|
|
||||||
// String Input
|
// String Input
|
||||||
String[] strings = {"c", "a", "e", "b","d"};
|
String[] strings = {"c", "a", "e", "b","d"};
|
||||||
//Output => a b c d e
|
//Output => e, d, c, b, a
|
||||||
print(bubbleSort.sort(strings));
|
print(bubbleSort.sort(strings));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -19,37 +19,34 @@ class CocktailShakerSort implements SortAlgorithm {
|
|||||||
**/
|
**/
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public <T extends Comparable<T>> T[] sort(T[] array){
|
public <T extends Comparable<T>> T[] sort(T[] array) {
|
||||||
|
|
||||||
int last = array.length;
|
int length = array.length;
|
||||||
|
int left = 0;
|
||||||
// Sorting
|
int right = length - 1;
|
||||||
boolean swap;
|
int swappedLeft, swappedRight;
|
||||||
do {
|
while (left < right) {
|
||||||
swap = false;
|
// front
|
||||||
|
swappedRight = 0;
|
||||||
//front
|
for (int i = left; i < right; i++) {
|
||||||
for (int count = 0; count <= last - 2; count++) {
|
if (less(array[i + 1], array[i])) {
|
||||||
if (less(array[count + 1], array[count])) {
|
swap(array, i, i + 1);
|
||||||
swap = swap(array, count, count + 1);
|
swappedRight = i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//break if no swap occurred
|
// back
|
||||||
if (!swap) {
|
right = swappedRight;
|
||||||
break;
|
swappedLeft = length - 1;
|
||||||
}
|
for (int j = right; j > left; j--) {
|
||||||
swap = false;
|
if (less(array[j], array[j - 1])) {
|
||||||
|
swap(array, j - 1, j);
|
||||||
//back
|
swappedLeft = j;
|
||||||
for (int count = last - 2; count >= 0; count--) {
|
|
||||||
if (less(array[count + 1], array[count])) {
|
|
||||||
swap = swap(array, count, count + 1);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
last--;
|
left = swappedLeft;
|
||||||
//end
|
}
|
||||||
} while (swap);
|
|
||||||
return array;
|
return array;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Driver Program
|
// Driver Program
|
||||||
|
Loading…
Reference in New Issue
Block a user