java排序算法_002鸡尾酒排序

package wzs.sort;

import java.util.Arrays;

//鸡尾酒排序,也就是定向冒泡排序, 鸡尾酒搅拌排序, 搅拌排序 (也可以视作选择排序的一种变形), 
//涟漪排序, 来回排序 or 快乐小时排序, 是冒泡排序的一种变形。此算法与冒泡排序的不同处在于排序时是以双向在序列中进行排序。
public class Test_wzs002
{
    public static void main(String[] args)
    {
        int[] intArray =
        {
                10, 3, 5, 7, 1, 9, 6, 2, 4, 8
        };
        cocktailSort(intArray);
        System.out.println("\n排序后:" + Arrays.toString(intArray));
    }

    /**
     * 鸡尾酒排序
     * @param intArray
     */
    private static void cocktailSort(int[] intArray)
    {
        int bottom = 0;// 索引开始位置
        int top = intArray.length - 1;// 索引结束位置
        boolean flag = true;// 控制排序停止

        int count = 0;// 记录排序次数
        while (flag)
        {
            flag = false;
            // 从左到右,升序
            for (int i = bottom; i < top; i++)
            {
                if (intArray[i] > intArray[i + 1])
                {
                    swap(intArray, i, i + 1);
                    flag = true;
                }
            }
            top--;
            // 从右到左,降序
            for (int j = top; j > bottom; j--)
            {
                if (intArray[j] < intArray[j - 1])
                {
                    swap(intArray, j, j - 1);
                    flag = true;
                }
            }
            bottom++;

            count++;// 一次比较结束+1
            System.out.println("第" + count + "次排序:" + Arrays.toString(intArray));
        }
    }

    /**
     * 数组元素替换
     * @param intArray 指定的数组
     * @param i 待替换的下标
     * @param j 替换的下标
     */
    private static void swap(int[] intArray, int i, int j)
    {
        int temp = intArray[i];
        intArray[i] = intArray[j];
        intArray[j] = temp;
    }
}

输出结果:

第1次排序:[1, 3, 5, 7, 2, 9, 6, 4, 8, 10]
第2次排序:[1, 2, 3, 5, 4, 7, 6, 8, 9, 10]
第3次排序:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
第4次排序:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

排序后:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值