您好我正在尝试对传递给函数的向量实现合并排序。这是我的代码,它不会对列表进行排序,但我不确定出了什么问题。当我输出原始向量和排序后的向量时,两者之间存在一些差异,但仍然没有排序。
void BestFit::findBest(){
vector<double> distances;
vector<double> sorted;
distances = getDistance(0);
printDistance(distances);
sorted = sortDistance(distances);
printDistance(sorted);
}
vector<double> BestFit::sortDistance(vector<double> distances){
int mid = distances.size()/2;
vector<double> left;
vector<double> right;
if(distances.size() > 1){
for(int i = 0; i < mid; i++){
left.push_back(distances[i]);
}
for(int i = mid; i < distances.size(); i++){
right.push_back(distances[i]);
}
return sortDistanceHelp(left, right);
}else{
return distances;
}
}
vector<double> BestFit::sortDistanceHelp(vector<double> left, vector<double> right){
vector<double> result;
if(left.size() > 1){
left = sortDistance(left);
}else if(right.size() > 1){
right = sortDistance(right);
}
int count = 0;
int left_count = 0;
int right_count = 0;
while(count < (left.size() + right.size())){
if(left_count < left.size() && right_count < right.size()){
if(left[left_count] <= right[right_count]){
result.push_back(left[left_count]);
left_count++;
}else{
result.push_back(right[right_count]);
right_count++;
}
}else if(left_count < left.size()){
result.push_back(left[left_count]);
left_count++;
}else{
result.push_back(right[right_count]);
right_count++;
}
count++;
}
return result;
}
这是未排序和排序的距离向量的输出。
未分类:
距离:0.679371 距离:1.263918 距离:1.575268 距离:0.117904 距离:3.851347 距离:2.317885 距离:0.899686 距离:3.916363 距离:1.513004 距离:0.446430
排序:
距离:0.679371 距离:1.263918 距离:1.575268 距离:0.117904 距离:2.317885 距离:0.899686 距离:3.851347 距离:3.916363 距离:1.513004 距离:0.446430