鸡尾酒排序与气泡排序相反,气泡排序是从左到右迭代元素,然后首先将最大的元素移到正确的位置,依此类推。在鸡尾酒式排序中,元素以交替方式在两个方向(左和右)上迭代。
以下是鸡尾酒排序的程序-
public class Demo{
static int temp;
static void Cocktail(int a[], int n){
boolean swap = true;
int begin = 0,i;
int end = n - 1;
while (swap) {
swap = false;
for (i = begin; i < end; ++i){
if (a[i] > a[i + 1]){
temp = a[i];
a[i]=a[i+1];
a[i+1]=temp;
swap = true;
}
}
if (!swap)
break;
swap = false;
for (i = end - 1; i >= begin; --i){
if (a[i] > a[i + 1]){
temp = a[i];
a[i]=a[i+1];
a[i+1]=temp;
swap = true;
}
}
++begin;
}
}
public static void main(String[] args) {
int my_arr[] = {34, 78, 90, 32, 67, 12, 1, 0, 95};
Cocktail(my_arr, my_arr.length);
System.out.println("The sorted array is ");
for (int i = 0; i < my_arr.length; i++)
System.out.print(my_arr[i]+" ");
System.out.println();
}
}
输出结果
The sorted array is
0 1 12 32 34 67 78 90 95
第一步,循环从左到右运行(类似于气泡排序),在此过程中,比较相邻项目。如果左手值大于右手值,则会交换这些值。第一次迭代结束后,将在数组末尾找到最大的元素。在下一步中,通过保留最新排序的项目,循环从右到左运行。在这里,再次比较相邻的元素,并将较大的元素添加到数组的末尾。