快速排序
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列
基本步骤
1.三数取中
在快排的过程中,每一次我们要取一个元素作为枢纽值,以这个数字来将序列划分为两部分。在此我们采用三数取中法,也就是取左端、中间、右端三个数,然后进行排序,将中间数作为枢纽值。
2.根据枢纽值进行分割
代码实现
//找到中间的数
int partition(vector<int> &list, int low /*开始索引*/, int high /*结束索引*/)
{
int mid = low + (high - low) / 2;
//找到中间值
if (list[low] > list[high])
swap(list[low], list[high]);
if (list[mid] > list[high])
swap(list[mid], list[high]);
if (list[mid] > list[low])
swap(list[low], list[mid]);
int pivotKey = list[low];
while (low < high)
{
while (high > low && list[high] >= pivotKey)
--high;
swap(list[high], list[low]);
while (low < high && list[low] <= pivotKey)
++low;
swap(list[low], list[high]);
}
return low;
}
//递归排序
void qSort(vector<int> &list, int low /*开始索引*/, int high /*结束索引*/)
{
if (low < high)
{
int pivot = partition(list, low, high);
qSort(list, low, pivot - 1);
qSort(list, pivot + 1, high);
}
}
void quickSort(vector<int> &list)
{
qSort(list, 0, list.size() - 1);
}
随机快排算法(最常用)
vector<int> partition(vector<int> &list, int left, int right)
{
vector<int> earge;
int less = left - 1;
int more = right;
int cur = left;
while (cur < more)
{
if (list[cur] < list[right])
{
swap(list[++less], list[cur++]);
}
else if (list[cur] > list[right])
{
swap(list[cur], list[--more]);
}
else
{
++cur;
}
}
swap(list[more], list[right]);
earge.push_back(less);
earge.push_back(++more);
return earge;
}
void qSort(vector<int> &list, int left, int right)
{
if (left >= right)
return;
else
{
srand(time(NULL));
int index = rand() % (right - left + 1) + left;
swap(list[index], list[right]);
vector<int> eargeIndex = partition(list, left, right);
qSort(list, left, eargeIndex[0]);
qSort(list, eargeIndex[1], right);
}
}
void quickSort(vector<int> &list)
{
qSort(list, 0, list.size() - 1);
}