基本思想
选择一个基准数,通过一趟排序将要排序的数据分割成独立的两部分;其中一部分的所有数据都比另外一部分的所有数据都要小。然后,再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
算法步骤
快速排序流程:
- 从数列中挑出一个基准值。
- 将所有比基准值小的摆放在基准前面,所有比基准值大的摆在基准的后面(相同的数可以到任一边);在这个分区退出之后,该基准就处于数列的中间位置。
- 递归地把"基准值前面的子数列"和"基准值后面的子数列"进行排序。
C++程序
Partition 分治
pivot 中心
算法不理解直接看图解算法
#include <iostream>
#define MaxSize 20 /*顺序表的最大长度为20*/
using namespace std;
int Partition(int A[], int low, int high)
{
int temp = A[low];
while (low < high)
{
while (low < high && A[high] >= temp)
{
--high;
}
A[low] = A[high];
while (low < high && A[low] <= temp)
{
++low;
}
A[high] = A[low];
}
A[low] = temp;
return low;
}
void QuickSort(int r[], int first, int end)
{
int pivot;
if(first < end) {
pivot = Partition(r, first, end);
QuickSort(r, first, pivot-1);
QuickSort(r, pivot + 1, end);
}
}
int main()
{
int i, n;
int r[MaxSize + 1];
cout<<"请输入顺序表的长度:"<<endl;
cin>>n;
if(n < 0 || n > 20) {
throw "参数不合法,请输入[0,20]之间的值!";
}
cout<<"请输入待排序的顺序表元素:"<<endl;
for(i = 1; i <= n; i++) {
cin>>r[i];
}
QuickSort(r, 1, n);
cout<<"快速排序之后的顺序表为:"<<endl;
for(i = 1; i <= n; i++)
cout<<r[i]<<" ";
cout<<endl;
return 0;
}
图解算法
数据如图所示,第一次进入pivot = Partition(r, first, end)
函数,
运行到int temp = A[low];
运行到
while (low < high && A[high] >= temp)
{
--high;
}
A[low] = A[high];
运行到
while (low < high && A[low] <= temp)
{
++low;
}
A[high] = A[low];
还在 while (low < high)
循环里面,再次进入
while (low < high && A[high] >= temp)
{
--high;
}
A[low] = A[high];
此时low<high
不满足了,没有进入到循环
while (low < high && A[low] <= temp)
{
++low;
}
A[high] = A[low];
退出大循环
while (low < high)
{
//里面就不写了,退出这个大循环了
}
A[low] = temp;
return low;
现在,pivot前面的数据都小于23,后面的数据都大于23。排序进行了一部分
退出Partition
函数,进入第五行QuickSort(r, first, pivot-1);
递归
void QuickSort(int r[], int first, int end) {
int pivot;
if(first < end) {
pivot = Partition(r, first, end);
QuickSort(r, first, pivot-1);
QuickSort(r, pivot + 1, end);
}
}
如果觉得有用,请三连加评论。