直接上代码!!!!
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
void Swap(vector<int>T_vec, int max_idx, int min_idx)
{
int Temp_val = T_vec[max_idx];
T_vec[max_idx] = T_vec[min_idx];
T_vec[min_idx] = Temp_val;
}
int Partition(vector<int>& T_vec, int B_idx, int E_idx)
{
int M_idx = B_idx + (E_idx - B_idx) / 2;
//找一个适合的值作为轴值,不一定是最中间的值
if (T_vec[B_idx] > T_vec[E_idx])
{
Swap(T_vec, B_idx, E_idx);
}
if (T_vec[M_idx] > T_vec[E_idx])
{
Swap(T_vec, M_idx, E_idx);
}
if (T_vec[M_idx] > T_vec[B_idx])
{
Swap(T_vec, M_idx, B_idx);
}
int Pivot_val = T_vec[B_idx];
int Temp_val = Pivot_val;
//大于轴值的放到轴值的右边,小于的放到左边
while (B_idx < E_idx)
{
while (B_idx < E_idx && T_vec[E_idx] >= Pivot_val)
{
--E_idx;
}
T_vec[B_idx] = T_vec[E_idx];
while (B_idx < E_idx && T_vec[B_idx] <= Pivot_val)
{
++B_idx;
}
T_vec[E_idx] = T_vec[B_idx];
}
//此时的B_idx是 = E_idx的所有就是在最中间的位置
//以为交换的过程中轴值是会发生变化的,所以在到存的轴值放回原处,最后放回其下标
T_vec[B_idx] = Temp_val;
return B_idx;
}
void QSort(vector<int>& T_vec, int B_idx, int E_idx)
{
while (B_idx < E_idx)
{
int Pivot_idx = Partition(T_vec, B_idx, E_idx);
QSort(T_vec, B_idx, Pivot_idx - 1);//先对低位的进行排序
B_idx = Pivot_idx + 1;//对高为的进行排序
}
}
void QuickSort(vector<int>& T_vec)
{
QSort(T_vec, 0, T_vec.size() - 1);
}
void Text()
{
vector<int> T_vec;
srand((unsigned)time(nullptr));
cout << "输入需要排序的个数: " << "\n";
int Num;
cin >> Num;
while (Num > 0)
{
T_vec.emplace_back(rand() % 10);
--Num;
}
cout << "排序前: ";
for (vector<int>::iterator it = T_vec.begin(); it != T_vec.end(); ++it)
{
cout << *it << " ";
}
cout << "\n";
cout << "排序后: ";
QuickSort(T_vec);
for (vector<int>::iterator it = T_vec.begin(); it != T_vec.end(); ++it)
{
cout << *it << " ";
}
cout << "\n";
}
int main()
{
Text();
system("pause");
return 0;
}