方式一 交换元素
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
using namespace std;
void quickSort(vector<int>& vec, int first, int end)
{
if (first >= end)
return;
int temp = vec[first];
int l = first;
int r = end;
while (l < r)
{
//while (l < r && vec[l] <= temp) l++; 错误
while (l < r && vec[r] >= temp) r--; //先移动右边
while (l < r && vec[l] <= temp) l++; //再移动左面
if(l < r)
swap(vec[l], vec[r]);
}
swap(vec[first], vec[l]); //最终将基准数归位
quickSort(vec, first, l - 1); //继续处理左边的,这是一个递归的过程
quickSort(vec, l + 1, end); //继续处理右边的,这是一个递归的过程
}
int main()
{
int arr[] = { 2,56,7,88,100,24,54,11 };
vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
for (int x : vec)
{
cout << x << " ";
}
cout << endl;
quickSort(vec, 0, vec.size() - 1);
for (int x : vec)
{
cout << x << " ";
}
system("pause");
return 0;
}
经过本地运行,确保程序是准确的
方式二 赋值
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
using namespace std;
void quickSort(vector<int>& vec, int first, int end)
{
if (first >= end)
return;
int temp = vec[first]; //temp存的就是基准数
int l = first;
int r = end;
while (l < r)
{
//顺序很重要,要先从右边开始找
while (l < r && vec[r] >= temp)
{
r--;
}
if(l < r)
//vec[l+++] = vec[r];
vec[l] = vec[r];
//再找左边的
while (l < r && vec[l] <= temp)
{
l++;
}
if(l < r)
//vec[r--] = vec[l];
vec[r] = vec[l];
}
//最终将基准数归位
vec[l] = temp;
quickSort(vec, first, l - 1); //继续处理左边的,这是一个递归的过程
quickSort(vec, l + 1, end);//继续处理右边的,这是一个递归的过程
}
int main()
{
int arr[] = { 2,56,7,88,100,24,54,11 };
vector<int> vec(arr, arr + sizeof(arr) / sizeof(int));
for (int x : vec)
{
cout << x << " ";
}
cout << endl;
quickSort(vec, 0, vec.size() - 1);
for (int x : vec)
{
cout << x << " ";
}
system("pause");
return 0;
}