我想按它们的 x 对 n 维点的列表进行排序并存储它们的原始索引:
original=[(3,2,3)(1,2,1)(5,1,5)]
排序后:
[(1,2,1)(3,2,3)(5,1,5)]
和索引:
store=[1,0,2]
我曾经vector< vector<double>
存储n维点:
a[0][0] = x, a[0][1] = y, a[0][2] = z, ...
我写了一个合并排序来做到这一点,source
通过引用传输调用并通过引用传输result
调用以获取索引。
我遇到了一个问题,如果我想打印结果,程序就会关闭。
#include <vector>
#include <cmath>
#include <cfloat>
#include <iostream>
#include <algorithm>
using namespace std;
void merge(vector< vector<double> >& source, vector< int >& result, int lmin, int lmax, int rmin, int rmax){
int i = lmin, j = rmin;
while(i <= lmin && j <= rmin){
//left > right
if(source[i][0] > source[j][0]){
source[i].swap(source[j]);
//exchange result
int temp = result[j];
result[j] = result[i];
result[i] = temp;
i ++;
}
else if(source[i][0] < source[j][0])
source[i].swap(source[j]);
j ++;
}
}
void merge_sort(vector< vector<double> >& source, vector< int >& result, int min, int max){
if(max - min == 0){
result[min] = min;
return;
}
int median = (max - min) / 2;
merge_sort(source, result, min , median);
merge_sort(source, result, median + 1 , max);
merge(source, result, min, median, median + 1, max);
}
int main(){
vector < vector<double> >test (8, vector<double>(3));
vector < int >result (8);
vector < vector<double> >ttt;
test[0][0]= 10;
test[0][1]= 20;
test[0][2]= 30;
//(1,2,3)
test[1][0]= 1;
test[1][1]= 2;
test[1][2]= 3;
//(1000,2000,3000)
test[2][0]= 1000;
test[2][1]= 2000;
test[2][2]= 3000;
//(100,200,300)
test[3][0]= 100;
test[3][1]= 200;
test[3][2]= 300;
//(100,200,300)
test[4][0]= 100;
test[4][1]= 200;
test[4][2]= 302;
//(100,200,300)
test[5][0]= 100;
test[5][1]= 200;
test[5][2]= 3030;
//(100,200,300)
test[6][0]= 1000000;
test[6][1]= 2000000;
test[6][2]= 3000000;
test[7][0]= 10;
test[7][1]= 20;
test[7][2]= 30.5;
merge_sort(test, result, 0 , 7);
for (int i = 0; i < test.size(); i ++){
for(int j = 0; j < test[i].size(); j ++){
cout << test[i][j] << endl;
}
}
for(int i = 0; i < result.size(); i ++)cout << result[i] << endl;
}