(9)交換排序之二 快速排序

來源:互聯網
上載者:User

      快速排序(Quick
Sort)是對起泡排序的一種改進。它的基本思想是,通過一趟排序將待排序記錄分割成獨立的兩部分,其中一部分記錄的關鍵字均比另一部分記錄的關鍵字小,則可分別對這兩部分記錄繼續進行排序,以達到整個序列有序。

// 快速排序
void CExchangeSort::QuickSort(void)
{
const int count = 9, length = count -1;
int L[count] = {0, 49, 38, 65, 97, 76, 13, 27, 49};
int low = 1;
int high = length;
QuickSort(L, low, high);
//列印排序結果。
for (int i = 0; i <= length; ++ i)
{
cout << L[i] << "\t";
}
cout << endl;
}


// 快速排序之遞迴
void CExchangeSort::QuickSort(int L[], int low , int high)
{
if (low < high)
{
int pivotloc = Partition(L, low, high); //拿到樞軸記錄的位置
QuickSort(L, low, pivotloc - 1);
QuickSort(L, pivotloc + 1, high);
}
}


// 快速排序之分區
int CExchangeSort::Partition(int L[], int low , int high)
{
L[0] = L[low];
int pivotkey = L[low];
while(low < high)
{
while (low < high && L[high] >= pivotkey)
-- high;
L[low] = L[high];
while (low < high && L[low] <= pivotkey)
++ low;
L[high] = L[low];
}
L[low] = L[0];
return low;
}

      首先拿到樞軸位置,然後對低於樞軸位置的序列進行分區(也是排序的一個過程),再對高於樞軸位置的序列進行同樣的操作。如上面的序列。第一次分區後序列中,元素[1]到[8]變成27, 38, 13, 49, 76, 97, 65, 49。4是樞軸位置。很明顯元素[4]之前都是小於49的,[4]之後的關索引值都是大於等於49的。同樣對元素[1]...[4]和元素[5]...[8]這兩段再分別進行Partition的過程。如此遞迴,直到low不小於high,說明連續兩個元素都進行了比較。遞迴依次返回。

聯繫我們

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