Я рекомендую разделить метод на куски, которые вы можете понять, например:
public static boolean swap(int[] numbers, int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
return true;
}
static boolean leftSide(int[] numbers, int i, int j) {
boolean swapped = false;
for (int k = i; k < j; k++)
if (numbers[k] > numbers[k + 1])
swapped = swap(numbers, k, k + 1);
return swapped;
}
static boolean rightSide(int[] numbers, int i, int j) {
boolean swapped = false;
for (int k = j; k > i; k--)
if (numbers[k] < numbers[k - 1])
swapped = swap(numbers, k, k - 1);
return swapped;
}
public static void cocktailSort(int[] numbers) {
boolean swapped = true;
int i = -1;
int j = numbers.length - 1;
while (i++ < j && swapped)
if (swapped = leftSide(numbers, i, j))
swapped = rightSide(numbers, i, j--);
}
И проверить его:
public static void main(String[] args) {
int x[] = new int[] { 2, 6, 3, 7, 8, 3, 7, 5, 4 };
cocktailSort(x);
System.out.println(java.util.Arrays.toString(x));
}
Вывод:
[2, 3, 3, 4, 5, 6, 7, 7, 8]