Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include "util.

h"
int partition(vector<int> &vec, int p, int r)
{
int pivot = vec.at(r);
int i = p - 1;
for (int j = p; j < r ;j++)
{
if(vec.at(j) <= pivot)
{
i++;
swap(&vec.at(i), &vec.at(j));
}
}
swap(&vec.at(i + 1), &vec.at(r));
return i + 1;
}
void qSort(vector<int> &vec, int p, int r)
{
if(p < r)
{
int q = partition(vec, p, r);
qSort(vec, p, q - 1);
qSort(vec, q + 1, r);
}
}
int rand_partition(vector<int> &vec, int p, int r)
{
int i = randomInt(p, r);
swap(&vec.at(i), &vec.at(r));
return partition(vec, p, r);
}
void random_qSort(vector<int> &vec, int p, int r)
{
if (p < r) {
int q = rand_partition(vec, p, r);
random_qSort(vec, p, q-1);
random_qSort(vec, q+1,r);
}
}
int main()
{
vector<int> vec = createRandomArrInt(20, 100, 300);
printf("Before sort : \n");
printVec(vec);
//qSort(vec, 0, vec.size() - 1);
random_qSort(vec, 0, vec.size() - 1);
printf("After sort : \n");

printVec(vec);
getchar();
}

You might also like