鉴于2D数组,PearsonArray [100] [100],我将如何根据双PearsonArray [] []降序排序.pearson_correlation?行只是整数,列是结构(如下所示)。
结果数据如下所示:
ROW 0:
[0] ==> [TEST_USER:201,TRAIN_USER:13,CORRELATION:0.2222194792894441
[1] ==> [TEST_USER:201,TRAIN_USER:15,CORRELATION:0.9549380840555494
[2] ==> [TEST_USER:201,TRAIN_USER:52,CORRELATION:0.8741572761215378
[3] ==> [TEST_USER:201,TRAIN_USER:54,CORRELATION:0.9930549935286451
[4] ==> [TEST_USER:201,TRAIN_USER:62,CORRELATION:0.37139067635410394
[5] ==> [TEST_USER:201,TRAIN_USER:63,CORRELATION:0.8904703363154174
public class myPearsonStruct {
int testUserID;
int trainUserID;
double pearson_correlation;
public myPearsonStruct(int tester, int trainer, double correlation){
this.testUserID = tester;
this.trainUserID = trainer;
this.pearson_correlation = correlation;
}
}
答案 0 :(得分:1)
我想你想按照pearson_correlation字段的顺序在一维中对类myPearsonStruct的实例进行排序(也许你想要使用Capital" M"作为类名)。
您可以使用Arrays.sort方法进行排序。但是你必须先将你的二维数组转换为一维。如何订购并不重要,因为无论如何你都要进行分类。
例如,
myPearsonStruct[] mpsArray = new myPearsonStruct[100*100];
for(int i=0;i<100;i++) {
for(int j=0;j<100;j++) {
mpsArray[i*100+j] = PearsonArray[i][j];
}
}
然后,您需要实现一个Comparable接口来指定如何确定顺序。
public class PearsonComparator implements Comparator<myPearsonStruct> {
public int compare(myPearsonStruct o1, myPearsonStruct o2) {
// descending order
if (o1.pearson_correlation < o2.pearson_correlation) return 1;
else if (o1.pearson_correlation > o2.pearson_correlation) return -1;
else return 0;
}
}
使用两段代码,您可以轻松地对数据进行排序:
Arrays.sort(mpsArray, new PearsonComparator());
结果将放在mpsArray。