java排序演算法_002雞尾酒排序

來源:互聯網
上載者:User
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]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.