基本思想
任取一个元素为中心,所有比它小的元素一律前放,比他大的元素一律后放,形成左右两个子表;对各子表重新选择中心元素并依此规则调整,直到每个子表的元素只剩一个。
通过一趟排序,将待排序记录分割成独立的两部分,其中一部分记录的关键字都比两一部分记录的关键字小,则可对这两部分记录进行排序,以达到整个序列有序。
调试代码
cpp
#include <iostream>
#include <vector>
using namespace std;
int counter = 0;//调试用
int Partition(vector<int>&vec, int low, int high)
{
//首先以第一个元素的值作为枢轴的值,此时它所在的位置空出来,然后从后往前遍历,将第一个小于枢轴的值的元素放到空位
int pivotVal = vec[low]; // 选取第一个元素的值作为枢轴的值
while (low < high)
{
while (low < high && vec[high] >= pivotVal) high--; // 从后往前遍历,直到遇到比枢轴小的元素时停下
swap(vec[low], vec[high]);
while (low < high && vec[low] <= pivotVal) low++; // 从前往后遍历,直到遇到比枢轴大的元素时停下
swap(vec[low], vec[high]);
}
vec[low] = pivotVal;
cout << "第" << ++counter << "趟: ";
for (int i = 0; i < 11; i++)
cout << vec[i] << " ";
cout << endl << endl;
return low;
}
void quick_sort(vector<int>& vec, int low, int high)
{
if (low < high)
{
int pivot = Partition(vec, low, high); // 确定枢轴的位置
quick_sort(vec, low, pivot - 1); // 对 左边子序列 递归排序
quick_sort(vec, pivot + 1, high); // 对 右边子序列 递归排序
}
}
int main(int argc, const char* argv[])
{
vector<int> vec = { 100, 1, 53, 5, 36, 7, 8, 109, 10, 11, 15 };
cout << "待排序数组: ";
for (int i = 0; i < 11; i++)
cout << vec[i] << " ";
cout << endl << endl;
quick_sort(vec, 0, vec.size() - 1);
cout << "结果: ";
for (int i = 0; i < 11; i++)
cout << vec[i] << " ";
cout << endl << endl;
return 0;
}