Loading…
Loading…
A bidirectional bubble sort: each round bubbles the largest to the right, then the smallest to the left, closing in from both ends.
Start cocktail shaker sort.
1void cocktailSort(int[] arr) {2 int left = 0, right = arr.length - 1;3 while (left < right) { // shrink from both ends4 for (int i = left; i < right; i++) // forward pass5 if (arr[i] > arr[i+1]) swap(arr, i, i+1); // bubble larger right6 right--; // max settled at right7 for (int i = right; i > left; i--) // backward pass8 if (arr[i-1] > arr[i]) swap(arr, i-1, i); // bubble smaller left9 left++; // min settled at left10 }11}12 13void swap(int[] arr, int i, int j) {14 int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;15}