我有一个双精度的2D向量,我需要使用quicksort对其进行排序。但是,当我打印所有步骤时,似乎无法正常工作。 我的向量是一个全局变量,我尝试对每一行进行排序并在每次迭代后打印当前向量。
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 ind) {
if (low < high) {
int pi = partition(low,high,ind);
Sort(low,pi - 1,ind);
Sort(pi + 1,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;
}