I am attempting to write a QuickSort method in C++. I think my issue is with:
if( i <= j )
Because this is not comparing the values in the vector but my index. I attempted to use the brackets operator [] to access the value but then the code consumes memory and doesn't end on its own.
Also i would prefer to keep it a single method instead of splitting it into a method to partition and a method to sort.
STD::sort is implemented elsewhere along with other sort methods. I am just having trouble writing this one; and my input is restricted to a vector.
This is what i have
vector<double> QuickSort(vector<double> & vec1){
double i = 0;
double j = vec1.size()-1;
int size = vec1.size();
double tmp;
double pivot = vec1[(i + j) / 2];
// partition
while (i <= j) {
while (vec1[i] < pivot)
i++;
while (vec1[j] > pivot)
j--;
if (vec1[j] <= vec1[j-1]) {
tmp = vec1[j-1];
vec1[j-1] = vec1[j];
vec1[j] = tmp;
i++;
j--;
}
}
// recursion
if (vec1[i] > vec1[i+1]) {
QuickSort(vec1);
}
if (vec1[j] <vec1[j-1]) {
QuickSort(vec1);
}
return vec1;
}
Suggestions and advice please.