#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace Std;
/*
Function: Returns a random integer between (Min,max)
Parameter: min--minimum limit for return value
max--maximum limit of return value
*/
int random (int min,int max)
{
Srand ((unsigned) time (NULL));//Set the source of the random number
Return rand ()% (max-min+1) +min;
}
/*
Function: Moves the data of the array r position to the corresponding position,
So that the elements on the left are smaller than the array r, and the elements on the right are greater than r;
Parameter: a--array to manipulate
p--the starting position of the array to manipulate (not necessarily the first element of the array)
r--the terminating position of an array of operations (not necessarily the terminating element of the array)
Return value: The last position of the original array R
Description: A delivery address is required because the container used is passed as a value
*/
Int Partition (vector<int> &a, int p, int r)
{
int x = a[r];
int i = p-1;
int flag;
for (int j = p; J <= (R-1); j + +)
{
if (a[j]<=x)
{
I = i + 1;//record where the last element needs to be moved
flag = a[i];//Will A[i ] to exchange with A[J]
A[i] = a[j];
A[J] = flag;
}
}
flag = a[i+1];//Inserts the array r to the appropriate place
a[i+1] = a[r];
A[R] = flag;
Return (i + 1);
}
void Quitsort (vector<int> &a, int p, int r)
{
int q;
if (P < r)
{
Q = Partition (A, p, R);
Quitsort (A, p, q-1);
Quitsort (A, q + 1, r);
}
}
/*
To compensate for the uneven distribution of the fast sorting, the last data is randomly selected
*/
int randompartition (vector<int> &a, int p, int r)
{
int i = random (P, R);
int flag = 0;
flag = A[i];
A[i] = A[r];
A[R] = flag;
Return Partition (A, p, R);
}
void Randomquitsort (vector<int> &a, int p, int r)
{
int q;
if (P < r)
{
Q = randompartition (A, p, R);
Randomquitsort (A, p, q-1);
Randomquitsort (A, q + 1, R);
}
}
int main ()
{
Vector<int> A ({2,8,7,1,3,5,6,4});
Vector<int>::iterator i = A.begin ();
int j = 0;
int q = 0;
Quitsort (A, 0, A.size ()-1);
for (j = 0; J < A.size (); j + +)
{
cout << A[j] << Endl;
}
Randomquitsort (A, 0, A.size ()-1);
for (j = 0; J < A.size (); j + +)
{
cout << A[j] << Endl;
}
Cin >> J;
}
If you find the code has a problem, hope to contact me, I am grateful
Random Quick Sort