快速排序(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,說明連續兩個元素都進行了比較。遞迴依次返回。