您的位置:首页 > 其它

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

2011-05-01 22:12 806 查看
快速排序(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,说明连续两个元素都进行了比较。递归依次返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: