C++ QuickSort 不排序
C++ QuickSort not sorting
void quickSort(vector<double> unsortedData, int leftBound, int rightBound) {
if (leftBound < rightBound) {
double i = partitionStep(unsortedData, leftBound, rightBound);
quickSort(unsortedData, leftBound, i-1);
quickSort(unsortedData, i + 1, rightBound);
}
}
double partitionStep(vector<double> unsortedData, int leftBound, int rightBound) {
double pivot = unsortedData[rightBound];
while (leftBound <= rightBound) {
while ((unsortedData[leftBound] < pivot)) {
leftBound++;
}
while ((unsortedData[rightBound] > pivot)) {
rightBound--;
}
if (unsortedData[leftBound] == unsortedData[rightBound]) {
leftBound++;
} else if (leftBound < rightBound) {
double temp = unsortedData[leftBound];
unsortedData[leftBound] = unsortedData[rightBound];
unsortedData[rightBound] = temp;
}
}
return rightBound;
}
我需要对双精度向量进行排序。此代码运行但向量未在末尾排序。这可能是我忽略的事情。想法?
您的 quickSort
例程的高级描述是:
- 将原始向量的副本和范围的端点作为输入
- 用副本做事
- 放弃副本
这不是特别有用。将输入参数更改为 vector<double>&
以便您使用 reference 对原始向量而不是副本进行操作。
void quickSort(vector<double> unsortedData, int leftBound, int rightBound) {
if (leftBound < rightBound) {
double i = partitionStep(unsortedData, leftBound, rightBound);
quickSort(unsortedData, leftBound, i-1);
quickSort(unsortedData, i + 1, rightBound);
}
}
double partitionStep(vector<double> unsortedData, int leftBound, int rightBound) {
double pivot = unsortedData[rightBound];
while (leftBound <= rightBound) {
while ((unsortedData[leftBound] < pivot)) {
leftBound++;
}
while ((unsortedData[rightBound] > pivot)) {
rightBound--;
}
if (unsortedData[leftBound] == unsortedData[rightBound]) {
leftBound++;
} else if (leftBound < rightBound) {
double temp = unsortedData[leftBound];
unsortedData[leftBound] = unsortedData[rightBound];
unsortedData[rightBound] = temp;
}
}
return rightBound;
}
我需要对双精度向量进行排序。此代码运行但向量未在末尾排序。这可能是我忽略的事情。想法?
您的 quickSort
例程的高级描述是:
- 将原始向量的副本和范围的端点作为输入
- 用副本做事
- 放弃副本
这不是特别有用。将输入参数更改为 vector<double>&
以便您使用 reference 对原始向量而不是副本进行操作。