快速排序演算法(Java實現)__編碼

來源:互聯網
上載者:User

1、基本思想

通過一趟排序將要排序的資料分割成獨立的兩部分,其中一部分的所有資料都比另外一部分的所有資料都要小,然後再按此方法對這兩部分資料分別進行快速排序,整個排序過程可以遞迴進行,以此達到整個資料變成有序序列。

2、演算法步驟 獲得待排序數組 選取合適的數字作為排序基準數字(一般情況下選取數組或者子數組的第一個數字)。 將待排序數組中比基準數字小的放在基準數位左邊得到sub1,比基準數字大的放在基準數位右邊得到sub2。 如果sub1或者sub2隻有一個元素,那麼直接返回,否則就遞迴重排sub1或sub2。

3、Java代碼實現

public class QuickSort {    /**     * @Comment 快速排序一     * @Author Ron     * @Date 2017年10月25日 下午12:12:32     * @return     */    static void quikSort(int[] sources,int leftIndex,int rightIndex){        if(leftIndex >= rightIndex){            //如果左下標大於等於右下標,證明排序後得到的子數組元素個數小於等於1,排序完成,直接返回            return;        }        int startIndex = boundary(sources,leftIndex,rightIndex);        quikSort(sources,leftIndex,startIndex-1);        quikSort(sources,startIndex+1,rightIndex);    }    /**     * @Comment 二分待排序數組     * @Author Ron     * @Date 2017年10月25日 下午12:12:24     * @return     */    static int boundary(int[] sources,int leftIndex,int rightIndex){        int startIndex=leftIndex;        int endIndex = rightIndex;        int baseNum = sources[leftIndex];        while (startIndex < endIndex) {            while (startIndex < endIndex && sources[endIndex] >= baseNum) {                endIndex--;            }            sources[startIndex]=sources[endIndex];            while (startIndex < endIndex && sources[startIndex] <= baseNum) {                startIndex++;            }            sources[endIndex]=sources[startIndex];        }        sources[startIndex]=baseNum;        return startIndex;    }    public static void main(String[] args) {        int[] sources={3,9,4,1,7,6,2,0,8};        quikSort(sources,0,sources.length-1);        String result="";        for(int i = 0 ; i < sources.length ; i++){            result += sources[i]+"  ";        }        System.out.println(result);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.