#include <iostream>
using namespace std;
void quickSort(int* arr, int left, int right)
{
// 递归退出条件
if (left >= right)
return;
int l = left;
int r = right;
int pivot = arr[l]; // 比较值,可以随机选择一个
while (l < r)
{
// 从左边选择大于pivot的值
while (arr[l] < pivot)
l++;
// 从右边选出小于pivot的值
while (arr[r] > pivot)
r--;
// 判断是否需要交换
if (l <= r)
{
int tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
// 过滤掉当前交换值-i递增/j递减
l++;
r--;
}
}
// 递归
if (left < r)
quickSort(arr, left, r);
if (l < right)
quickSort(arr, l, right);
}
int main(void)
{
int arr[] = { 10, 58, 4, 47, 54, 12, 39, 65, 28, 79, 81, 26, 76, 102, 31, 46, 33, 27 };
int len = sizeof(arr) / sizeof(arr[0]);
cout << "排序前:" << endl;
for (size_t i = 0; i < len; i++)
cout << arr[i] << " ";
cout << endl;
quickSort(arr, 0, len - 1);
cout << "排序后:" << endl;
for (size_t i = 0; i < len; i++)
cout << arr[i] << " ";
cout << endl;
system("pause");
return 0;
}
03-15
1669
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)