快速排序的C++版

來源:互聯網
上載者:User

標籤:bsp   程式   經曆   快速   位置   UI   i+1   函數   return   

int Partition(int a[], int low, int high){    int x = a[high];//將輸入數組的最後一個數作為主元,用它來對數組進行劃分    int i = low - 1;//i是最後一個小於主元的數的下標    for (int j = low; j < high; j++)//遍曆下標由low到high-1的數    {        if (a[j] < x)//如果數小於主元的話就將i向前挪動一個位置,並且交換j和i所分別指向的數        {            int temp;            i++;            temp = a[i];            a[i] = a[j];            a[j] = temp;        }    }    //經曆上面的迴圈之後下標為從low到i(包括i)的數就均為小於x的數了,現在將主元和i+1位置上面的數進行交換    a[high] = a[i + 1];    a[i + 1] = x;    return i + 1;}void QuickSort(int a[], int low, int high){    if (low < high)    {        int q = Partition(a, low, high);        QuickSort(a, low, q - 1);        QuickSort(a, q + 1, high);    }}

 

partition函數的運行過程使用一個例子來協助理解。對數組[6, 10, 10, 3, 7 ,1,8]運行一次Partition函數的過程如(有黃色填充的部分代表主元)所示:

其中i和j分別是程式當中的兩個下標,j的作用是迴圈遍曆,i的作用是指向小於主元的最後的一個數。當迴圈結束之後就將主元和i+1位置上面的數進行交換,這樣就可以實現依據主元的大小對數組進行劃分。

快速排序的C++版

聯繫我們

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