1、算法思想
快速排序的基本思想是对输入的子数组a[p:r],按照以下三个步骤进行排序:
2、示例过程
最重要的就在于怎么去分割左右两边的元素。用画图的方法是最直接的。
【实现代码】
#include <iostream>
using namespace std;
/***********************************************************************
Input: a[]:待排数组序列 l:待排区间左下标,r:待排区间右下标
Output:
Description: 将数组序列的第一个元素作为枢纽元素x,将数组化分成
a[... x ...]。x左边的元素都小于x,右边的元素都大于x。
Return: 排序后枢纽元素的下标
Others:
************************************************************************/
template <class Type>
int Partition(Type a[],int l,int r)
{
Type x = a[l]; //枢纽元素(分割元素)
int i = l; //枢纽元素的索引号
int j = r; //a[]序列右边界索引号
while(i < j)
{
//从序列最右边开始查找,找到一个小于a[l]的为止;
while (a[j] >= x && i < j) --j;
if(i < j)
{
a[i] = a[j];
i++;
}
//从a[l]后面元素开始查找,找到一个比a[l]大的为止;
while (a[i] < x && i < j) ++i;
if (i < j)
{
a[j] = a[i];
j--;
}
}
a[i] = x; //将a[i]的值写回
return i; //返回分割点的索引
}
/***********************************************************************
Input: a[]:待排数组序列 l:待排区间左下标,r:待排区间右下标
Output:
Description: a[l...r]数组序列快速排序,按照升序
Return:
Others:
************************************************************************/
template <class Type>
void QuickSort(Type a[], int l, int r)
{
if (l < r)
{
int q = Partition(a, l, r); //以p为分割点进行分割
QuickSort(a, l, q-1); //快速排序左半段
QuickSort(a, q+1, r); //快速排序右半段
}
}
int source[7] = {7,6,5,4,3,2,1};
int main()
{
for (int i=0;i<7;i++)
{
cout<<source[i]<<" ";
}
cout<<endl;
QuickSort(source,0,6);
for (int i=0;i<7;i++)
{
cout<<source[i]<<" ";
}
cout<<endl;
return 0;
}