Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Cocktail Shaker Sort in Java #595

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions java/sorting/Cocktail_Shaker_Sort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
public class Cocktail_Shaker_Sort {

// 主排序方法
public static void cocktailShakerSort(int[] array) {
boolean swapped = true; // 标记是否有交换
int start = 0; // 当前排序的开始索引
int end = array.length - 1; // 当前排序的结束索引

while (swapped) {
swapped = false;

// 从左到右进行冒泡
for (int i = start; i < end; i++) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
swapped = true;
}
}
// 如果没有交换,说明数组已排序
if (!swapped) {
break;
}

// 更新结束索引
end--;

swapped = false;

// 从右到左进行冒泡
for (int i = end; i > start; i--) {
if (array[i] < array[i - 1]) {
swap(array, i, i - 1);
swapped = true;
}
}
// 更新开始索引
start++;
}
}

// 交换数组中两个元素的方法
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

// 主方法
public static void main(String[] args) {
int[] array = {5, 3, 8, 4, 2, 7, 1, 6};
System.out.println("原数组:");
printArray(array);

cocktailShakerSort(array);

System.out.println("排序后数组:");
printArray(array);
}

// 打印数组的方法
private static void printArray(int[] array) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}