I have a 2D vector of doubles, and I need to sort it using quicksort. However, when I print all the steps, it seems it's not working the way it should. My vector is a global variable, I try to sort each row and print the current vector after each iteration.
vector<vector<double>> vect;
int rows, cols;
void Print2DArray() {
for (int i = 0;i < vect.size();++i) {
for (int j = 0;j < vect[i].size();++j) {
cout << vect[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
int partition(int low, int high, int ind) {
double pivot = vect[ind][high];
int i = low;
double tmp;
for (int j = low;j <= high - 1;++j) {
if (vect[ind][j] <= pivot) {
tmp = vect[ind][j];
vect[ind][j] = vect[ind][i];
vect[ind][i] = tmp;
i++;
}
}
tmp = vect[ind][high];
vect[ind][high] = vect[ind][i];
vect[ind][i] = tmp;
Print2DArray();
return i;
}
void Sort(int low, int high, int ind) {
if (low < high) {
int pi = partition(low, high, ind);
Sort(low, pi - 1, ind);
Sort(pi + 1, high, ind);
}
}
void TwoDimSort() {
for (int i = 0;i < vect.size();++i) {
Sort(0, vect[i].size() - 1, i);
}
Print2DArray();
}
int main() {
rows = 3;
cols = 9;
srand((unsigned)time(NULL));
for (int i = 0;i < rows;++i) {
vector<double> tmp;
for (int j = 0;j < cols;++j) {
double num = (rand() % 100) * 0.9;
if (num > 0.0)
tmp.push_back(num);
}
vect.push_back(tmp);
}
Print2DArray();
TwoDimSort();
Print2DArray();
getchar();
return 0;
}